<?php
// +----------------------------------------------------------------------
// | Copyright (c) 中犇科技 All rights reserved.
// +----------------------------------------------------------------------

namespace app\automatic\controller\m2979;

use app\automatic\model\m2979\Freeinterface as FreeinterfaceModel;
use app\crm\model\Contract as ContractModel;
use app\spread\model\Free;
use app\spread\model\FreeProperty;
use app\spread\model\FreeFieldRule;
use app\crm\model\CrmChangeFieldLog;
use app\spread\model\SpreadDataConfig;
use app\spread\server\FreeFormulaApplyService;
use app\member\service\BusinessPlan;
use app\member\model\MemberConfig;
use app\spread\model\FreeNavConfig;
use service\Format;
use think\App;
use think\Exception;

use app\spread\controller\Free as Base;
use app\member\model\FreeTable;
use app\spread\model\SpreadBtnConfig;
use think\Db;

use app\spread\model\Free as MapModel;
use app\member\service\MemberCache;
use app\member\model\MemberRole;
use app\spread\model\FreeTableConfig;
use app\spread\model\Spread as SpreadModel;
use app\member\model\User;
use app\member\model\MemberMenu;
use app\spread\model\FreeTableSidebar;
use app\spread\model\TableGroup;
use app\spread\model\FreeField;
use app\statistics\model\StatisticsFormulaLog;
use app\statistics\service\StatisticsFormulaService;
use app\spread\model\FreeTabConfig;

use service\ApiReturn;

/**
 * 接口控制器
 * @package app\Freeinterface\controller
 */
class Freeinterface extends Base
{

     // 定义模块名
    protected $module = '';
    protected $primary_key = '';
    protected $table_name = '';
    protected $fixed = '';
    protected $table = '';
    protected $roles = '';
    protected $button_top = [];
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->module = 'freeinterface';
        $this->assign('alias',$this->module);
        $this->assign('table_name','lb_free_interface');

        $table = MemberCache::getTableInfoForAlias(MemberID, $this->module);
        $this->table = $table;
        $this->fixed = $table['fixed'];
        $this->primary_key = $table['primary_key'];
        $this->table_name = $table['table_name'];

        $role_ids = session('member_auth.roles');
        if (!is_array($role_ids)) {
            $role_ids = explode(',', $role_ids);
        }
        $this->roles = $role_ids;

        $this->button_top = [
            "1"=>["ident" => "add","title" => "新增","href"=>"add","class" =>"btn btn-sm mr5 btn-primary layeradd"],
            "2"=>["ident"=> "delete","title" =>  "批量删除","href" =>"delete","class" => "btn btn-sm mr5 btn-default ajax-post confirm","extra" =>[], "target-form"=>"ids"],
            "6"=>["ident" => "import",'title' => '导入',"href"=>"javascript:void(0);","icon" => "","class" =>"btn btn-default","onclick"=>"openImportStart()"],
            "9"=>["ident" => "export",'title' => '导出',"href"=>"javascript:void(0);","icon" => "","class" =>"btn btn-default","onclick"=>"openExportStart()"],
        ];
    }

    /**
     * 接口列表
     */
    public function index(){

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $map = $this->getMap();

        $tab_id = $map['tab_id'];
        // 封装where条件
        $where=[];
$whereStr='';
if (isset($map['freeinterface_aid'])) {
                        $where[] = ['freeinterface.aid', '=', $map['freeinterface_aid']];
                    }
if (isset($map['bumen'])) {
                            if (is_json($map['bumen']) == false) {
                                $dept_ids = explode(',',$map['bumen']);
                            } else {
                                $dept_ids = json_decode($map['bumen'], true);
                            }
                            if (!empty($dept_ids) && is_array($dept_ids) && count($dept_ids) > 0) {
                                foreach ($dept_ids as $deptid) {
                                    $whereStr .= 'find_in_set(' . $deptid . ',freeinterface.bumen) or ';
                                }
                                if ($whereStr != '') {
                                    $whereStr = substr_replace($whereStr, "", -4);
                                    $whereStr = '(' . $whereStr . ')';
                                }
                            } else {
                                $where[] = ['', 'exp', Db::raw("FIND_IN_SET({$dept_ids},freeinterface.bumen)")];
                            }
                        }
if (isset($map['yuangong'])) {
                        $user_ids = explode(',', $map['yuangong']);
                        foreach ($user_ids as $userid){
                            $whereStr .= 'find_in_set(' . $userid . ',freeinterface.yuangong) or ';
                        }
                        if ($whereStr != '') {
                            $whereStr = substr_replace($whereStr, "", -4);
                            $whereStr = '(' . $whereStr . ')';
                        }
                    }
if (isset($map['shengri'])) {
                        $tmp = explode(' - ', $map['shengri']);
                        if (isset($tmp[0]) && !empty($tmp[0])) {
                                $startTime = date("Y-m-d", (int)strtotime($tmp[0]));
                                $startTime = (int)strtotime($startTime);
                                $where[] = ['freeinterface.shengri', '>=', $startTime];
                            }
                            if (isset($tmp[1]) && !empty($tmp[1])) {
                                $endTime = date("Y-m-d 23:59:59", (int)strtotime($tmp[1]));
                                $endTime = (int)strtotime($endTime);
                                $where[] = ['freeinterface.shengri', '<=', $endTime];
                            }
                        }
if (isset($map['approve_status'])) {
                        $where[] = ['freeinterface.approve_status', 'like', "%".trim($map['approve_status'])."%"];
                    }
$adminInfo = getAuthUids();
                    if ($adminInfo['code'] != 1 && $adminInfo['uids']) {
                        $where[] = ['freeinterface.uid','in',$adminInfo['uids']];
                    }


        $condition_str = "";
        if (!empty($map['tab_id'])) {
            $tabConfigInfo = FreeTabConfig::where(['aid' => $map['tab_id']])->find();
            if (!$tabConfigInfo) {
                return ApiReturn::r(0, [], "数据有误");
            }
            if (!is_array($tabConfigInfo['condition'])) {
                $condition = json_decode($tabConfigInfo['condition'], true);
            }
            $newFree = new Free();
            $condition_str = $newFree->constructTreeConditionFormula($condition,0,$this->module);
        }

        //高级筛选
        $filterCondition = '';
        if(isset($map['filterCondition']) && count($map['filterCondition']) > 0){
            $newFree = new Free();
            $filterCondition = $newFree->constructTreeConditionFormula($map['filterCondition'], 0, $this->module, [], 1);
        }

        //选项卡搜索
        $navCondition = '';
        if(isset($map['nav_id']) && $map['nav_id'] != 0){
            $navInfo = FreeNavConfig::where('aid',$map['nav_id'])->field('condition')->find();
            $newFree = new Free();
            $navCondition = $newFree->constructTreeConditionFormula(json_decode($navInfo['condition'],true),0,$this->module,[],1);
        }
        // 排序
        $order = $this->getListOrder() ?: ['freeinterface.aid' =>'desc'];
;
        $params = input();
        $page = MemberCache::getDefaultPage($this->module, session('member_auth.member_id') ,$params['list_rows']);

        //查询数据
        $data_list = Db::table('lb_free_interface')->alias('freeinterface')->leftJoin('lb_free_form_ freeform', 'freeinterface.freeform_id = freeform.aid')->leftJoin('lb_free_generate_interface freegenerateinterface', 'freeinterface.freegenerateinterface_id = freegenerateinterface.aid')->where([
            ['freeinterface.is_del', '=', 0],
        ])->field('freeinterface.aid,freeinterface.riqixuanzeqi,freeinterface.shuzi,freeinterface.tupian1,freeinterface.tupian2,freeinterface.shipin1,freeinterface.freegenerateinterface_id as freegenerateinterface_id,freegenerateinterface.shoujihao as freegenerateinterface_shoujihao,freeinterface.freegenerateinterface_id_2 as freegenerateinterface_id_2,freeinterface.shoujihao_2 as freegenerateinterface_shoujihao_2,freeinterface.wenjian,freeinterface.xitongyuangong,freeinterface.duotu,freeinterface.lianjie,freeinterface.bianma,freeinterface.free_field_129071,freeinterface.weixin,freeinterface.shengshiqu,freeinterface.freeform_id as freeform_id,freeform.gongsimingcheng as freeform_gongsimingcheng,freeinterface.qiankuanjine,freeinterface.xuanxiang,freeinterface.cheng,freeinterface.shoujihao,freeinterface.bumen,freeinterface.yuangong,freeinterface.dituxuandian,freeinterface.wenjianshangchuan,freeinterface.touxiang,freeinterface.shipin,freeinterface.free_field_128868,freeinterface.free_field_128870,freeinterface.shengri,freeinterface.xingbie,freeinterface.aihao,freeinterface.create_id,freeinterface.update_time,freeinterface.create_time,freeinterface.status,freeinterface.sort,freeinterface.is_del,freeinterface.approve_status')->where($where)
            ->where($whereStr)
            ->where($condition_str)
            ->where($navCondition)
            ->where($filterCondition)
            ->order($order)
            ->group($this->module . '.aid')
            ->paginate($page);

        $page_statistics = getStatisitcsFromulaApplyInfo(['alias'=>$this->module, 'tab' => $tab_id, 'nav_id' => $map['nav_id'] ?? 0],$where);

        if (isset($map['export']) && $map['export']) {
            // 格式化数据
            foreach ($data_list as $key => $data) {
                $data_list[$key] = FreeProperty::handleDataToShowNew($this->module, $data, 0, 1);
            }

            return ApiReturn::r(1, $data_list, '导出成功');
        }

        // 获取表头统计
        if (isset($map['get_statistics']) && $map['get_statistics']) {
            return ApiReturn::r(1, $page_statistics, '成功');
        }

        if ($this->request->isPost()) {
            // 数据处理
            foreach ($data_list as $key => $data) {
                $data_list[$key] = FreeProperty::handleDataToShowForAutoCode($this->module, $data);
            }
            return ApiReturn::r(1, $data_list, '成功');
        }

        //列表显示字段
        $indexFields = [
['aid', 'ID', 'text', '', [], '', '',['type' => 'text', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128848', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['riqixuanzeqi', '日期选择器', 'text', '', [], '', '',['type' => 'diydate', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129110', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => 'HH:mm', 'json_data' => '{"useDiyTime":1}', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['shuzi', '数字', 'text', '', [], '', '',['type' => 'number', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129093', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['tupian1', '图片1', 'picture', '', [], '', '',['type' => 'image', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129097', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['tupian2', '图片2', 'picture', '', [], '', '',['type' => 'image', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129098', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['shipin1', '视频1', 'text', '', [], '', '',['type' => 'video', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129083', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['freegenerateinterface_shoujihao', '手机号', 'text', '', [], '', '',['type' => 'select-table', 'original_draw_type' => 'mobile', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129095', 'alias' => 'freegenerateinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => 'freegenerateinterface', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['freegenerateinterface_shoujihao_2', '手机号2', 'text', '', [], '', '',['type' => 'copy_field', 'original_draw_type' => 'mobile', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129096', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => 'freegenerateinterface', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['wenjian', '文件', 'files', '', [], '', '',['type' => 'files', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129084', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['xitongyuangong', '系统员工', 'text', '', ['0'=>['aid'=>'384',
'name'=>'总公司',
'child'=>['0'=>['aid'=>'386',
'name'=>'市场部',
'child'=>['0'=>['aid'=>'52355',
'name'=>'张无忌',
],
],
],
'1'=>['aid'=>'385',
'name'=>'销售部',
'child'=>['0'=>['aid'=>'396',
'name'=>'123',
'child'=>['0'=>['aid'=>'399',
'name'=>'218部门',
'child'=>[],
],
'1'=>['aid'=>'401',
'name'=>'218部门2',
'child'=>[],
],
],
],
],
],
'2'=>['aid'=>'389',
'name'=>'财务部',
'child'=>[],
],
'3'=>['aid'=>'25127',
'name'=>'李迪开发',
],
],
],
], '', '',['type' => 'system', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129057', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['duotu', '多图', 'pictures', '', [], '', '',['type' => 'images', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129068', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['lianjie', '链接', 'text', '', [], '', '',['type' => 'link', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129056', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['bianma', '编码', 'link', url('sidebar', ['alias' => 'freeinterface', 'id' => '__aid__', 'layer' => 1, 'open_target' => 'detail']), [], ' open_sidebar', '',['type' => 'code', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128887', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['free_field_129071', '使用微信数', 'text', '', [], '', '',['type' => 'census', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129071', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '0', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['weixin', '微信', 'text', '', [], '', '',['type' => 'text', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128954', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['shengshiqu', '省市区', 'text', '', [], '', '',['type' => 'address', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128922', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['freeform_gongsimingcheng', '公司名称', 'text', '', [], '', '',['type' => 'select-table', 'original_draw_type' => 'text', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129047', 'alias' => 'freeform', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => 'freeform', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['qiankuanjine', '欠款金额', 'text', '', [], '', '',['type' => 'money', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129048', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '2', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['xuanxiang', '选项', 'text', '', ['0'=>['name'=>'一',
'index'=>'0',
'aid'=>'1',
'is_default'=>'0',
],
'1'=>['name'=>'二',
'index'=>'1',
'aid'=>'2',
'is_default'=>'0',
],
'2'=>['name'=>'三',
'index'=>'2',
'aid'=>'3',
'is_default'=>'0',
],
'3'=>['name'=>'四',
'index'=>'3',
'aid'=>'4',
'is_default'=>'0',
],
'4'=>['name'=>'五',
'index'=>'4',
'aid'=>'5',
'is_default'=>'0',
],
], '', '',['type' => 'select', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129050', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['cheng', '昵称', 'text', '', [], '', '',['type' => 'text', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128862', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '-1', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['bumen', '部门', 'dept', '', ['0'=>['aid'=>'384',
'name'=>'总公司',
'child'=>['0'=>['aid'=>'386',
'name'=>'市场部',
],
'1'=>['aid'=>'385',
'name'=>'销售部',
'child'=>['0'=>['aid'=>'396',
'name'=>'123',
'child'=>['0'=>['aid'=>'399',
'name'=>'218部门',
],
'1'=>['aid'=>'401',
'name'=>'218部门2',
],
],
],
],
],
'2'=>['aid'=>'389',
'name'=>'财务部',
],
],
],
], '', '',['type' => 'dept', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128886', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['yuangong', '员工', 'system', '', ['0'=>['aid'=>'384',
'name'=>'总公司',
'pid'=>'0',
'child'=>['0'=>['aid'=>'386',
'name'=>'市场部',
'pid'=>'384',
'child'=>['0'=>['aid'=>'52355',
'name'=>'张无忌',
'roles'=>'491',
'pid'=>'386',
],
],
],
'1'=>['aid'=>'389',
'name'=>'财务部',
'pid'=>'384',
'child'=>[],
],
'2'=>['aid'=>'25127',
'name'=>'李迪开发',
'roles'=>'1',
'pid'=>'384',
],
],
],
], '', '',['type' => 'users', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128885', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', 'field_width' => '159']],
['dituxuandian', '地图选点', 'text', '', [], '', '',['type' => 'map', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128923', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['wenjianshangchuan', '文件上传', 'files', '', [], '', '',['type' => 'files', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128884', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '{"filesVerify":"","isCheckedverify":"0","maxUploadCount":"1"}', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['touxiang', '头像', 'picture', '', [], '', '',['type' => 'image', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128874', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['shipin', '视频', 'text', '', [], '', '',['type' => 'video', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128881', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '{"video_speed":"1","video_times":"1","video_hash":""}', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['free_field_128868', '订单使用次数', 'text', '', [], '', '',['type' => 'census', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128868', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '0', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['free_field_128870', '手机使用次数', 'text', '', [], '', '',['type' => 'census', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128870', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '0', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['shengri', '生日', 'text', '', [], '', '',['type' => 'date', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128863', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['xingbie', '性别', 'text', '', ['0'=>['name'=>'男',
'index'=>'0',
'aid'=>'1',
'is_default'=>'0',
],
'1'=>['name'=>'女',
'index'=>'1',
'aid'=>'2',
'is_default'=>'0',
],
'2'=>['name'=>'保密',
'index'=>'2',
'aid'=>'3',
'is_default'=>'0',
],
], '', '',['type' => 'select', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128864', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['aihao', '爱好', 'text', '', ['0'=>['name'=>'唱',
'index'=>'0',
'aid'=>'1',
'is_default'=>'0',
],
'1'=>['name'=>'跳',
'index'=>'1',
'aid'=>'2',
'is_default'=>'0',
],
'2'=>['name'=>'rap',
'index'=>'2',
'aid'=>'3',
'is_default'=>'0',
],
'3'=>['name'=>'篮球',
'index'=>'3',
'aid'=>'4',
'is_default'=>'0',
],
], '', '',['type' => 'selects', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128865', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['create_time', '创建时间', 'text', '', [], '', '',['type' => 'date', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128851', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['status', '状态', 'text', '', [], '', '',['type' => 'switch', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '128852', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
['approve_status', '审核状态', 'text', '', ['0'=>['aid'=>'0',
'name'=>'待发起',
],
'1'=>['aid'=>'1',
'name'=>'通过',
],
'2'=>['aid'=>'2',
'name'=>'拒绝',
],
'3'=>['aid'=>'3',
'name'=>'审核中',
],
'4'=>['aid'=>'4',
'name'=>'已撤销',
],
], '', '',['type' => 'approve', 'original_draw_type' => '', 'text_hidden' => '0', 'unit' => '', 'field_id' => '129086', 'alias' => 'freeinterface', 'fields_description' => '', 'show_roles' => '', 'edit_roles' => '', 'decimal_places' => '', 'date_format' => '', 'json_data' => '', 'video_config' => '', 'r_alias' => '', 'select_table_checkbox' => '0', 'select_table_multiple' => '0', ]],
];

        // 字段根据角色判断是否限制
        foreach ($indexFields as $key => $val) {
            //字段根据角色判断是否限制
            if (!in_array(1, $this->roles) && $val[7]['show_roles']) {
                $check_roles = explode(',', $val[7]['show_roles']);

                if (!array_intersect($this->roles, $check_roles)) {
                    unset($indexFields[$key]);
                    continue;
                }
            }
        }

        $indexFields[] = ['right_button', '操作','btn'];
        // 搜索显示字段
        $searchFields = [
['type' => 'dept', 'name' => 'bumen', 'field' => 'bumen', 'title' => '部门', 'tips' => '', 'extra'=>['0'=>['aid'=>'384',
'name'=>'总公司',
'child'=>['0'=>['aid'=>'386',
'name'=>'市场部',
],
'1'=>['aid'=>'385',
'name'=>'销售部',
'child'=>['0'=>['aid'=>'396',
'name'=>'123',
'child'=>['0'=>['aid'=>'399',
'name'=>'218部门',
],
'1'=>['aid'=>'401',
'name'=>'218部门2',
],
],
],
],
],
'2'=>['aid'=>'389',
'name'=>'财务部',
],
],
],
], 'value'=>input('param.bumen'),'default'=>input('param.bumen')],
['type' => 'users', 'name' => 'yuangong', 'field' => 'yuangong', 'title' => '员工', 'tips' => '', 'extra'=>['0'=>['aid'=>'384',
'name'=>'总公司',
'child'=>['0'=>['aid'=>'386',
'name'=>'市场部',
'child'=>['0'=>['aid'=>'52355',
'name'=>'张无忌',
],
],
],
'1'=>['aid'=>'385',
'name'=>'销售部',
'child'=>['0'=>['aid'=>'396',
'name'=>'123',
'child'=>['0'=>['aid'=>'399',
'name'=>'218部门',
'child'=>[],
],
'1'=>['aid'=>'401',
'name'=>'218部门2',
'child'=>[],
],
],
],
],
],
'2'=>['aid'=>'389',
'name'=>'财务部',
'child'=>[],
],
'3'=>['aid'=>'25127',
'name'=>'李迪开发',
],
],
],
], 'value'=>input('param.yuangong'),'default'=>input('param.yuangong')],
['type' => 'date', 'date_format' => '', 'name' => 'shengri', 'field' => 'shengri', 'title' => '生日', 'tips' => '','value'=>input('param.shengri'),'default'=>input('param.shengri'),'search_value'=>''],
['type' => 'text', 'name' => 'approve_status', 'field' => 'approve_status', 'title' => '审核状态', 'tips' => '', 'value'=>input('param.approve_status'),'default'=>input('param.approve_status')],
];

        $member_role = session('member_auth.roles');
        foreach ($searchFields as $key => &$val) {
            $default_value = '';
            $type_flag = in_array($val['type'], array('date', 'datetime', 'daterange', 'year', 'month', 'day'));
            if (isset($map[$val['name']])) {
                if ($map[$val['name']] !== "0" || !$type_flag) {
                    $default_value = $map[$val['name']];
                }
            } else {
                if (!empty($val['search_value'])) {
                    $default_value = FreeProperty::formatSearchValue($val['search_value'], $val['type'], $member_role);
                }
            }
            $val['default'] = $default_value;
        }

        // 自定义顶部操作按钮
        $list_choose_user_btn = [
];

        $member_id = session('member_auth.member_id') ?: MemberID;
        $uid = session('member_auth.uid') ?: MemberUID;
        $is_sub_admin = getSubAdmin($member_id, $uid);
        $roles = explode(',', getRoles($member_id, $uid));
        $auth = [
            'uid' => $uid,
            'is_sub_admin' => $is_sub_admin,
            'roles' => $roles
        ];

        // 右边按钮
        $right_button = ['0'=>['ident'=>'edit',
'title'=>'编辑',
'href'=>['0'=>'edit',
'1'=>['id'=>'__aid__',
'layer'=>'1',
'sidebar'=>'1',
'alias'=>'freeinterface',
'is_info'=>'1',
],
],
'class'=>'btn btn-xs mr5 btn-default layeredit',
'extra'=>['0'=>['field'=>'approve_status',
'compare'=>'6',
'dataVal'=>'1',
'logic'=>'1',
'fieldType'=>'approve',
'extra'=>['0'=>['aid'=>'0',
'name'=>'待发起',
],
'1'=>['aid'=>'1',
'name'=>'通过',
],
'2'=>['aid'=>'2',
'name'=>'拒绝',
],
'3'=>['aid'=>'3',
'name'=>'审核中',
],
'4'=>['aid'=>'4',
'name'=>'已撤销',
],
],
],
],
],
'1'=>['ident'=>'delete',
'title'=>'删除',
'href'=>['0'=>'setstatus',
'1'=>['ids'=>'__aid__',
'type'=>'delete',
'alias'=>'freeinterface',
],
],
'class'=>'btn btn-xs mr5 btn-default ajax-get confirm',
'extra'=>['0'=>['field'=>'aid',
'compare'=>'5',
'dataVal'=>'0',
'logic'=>'1',
],
],
],
'2'=>['btn_id'=>'6492',
'ident'=>'verify',
'title'=>'测试',
'href'=>['0'=>'hashApi',
'1'=>['alias'=>'freeinterface',
'layer'=>'1',
'aid'=>'__aid__',
'btn_config_id'=>'6492',
'hash'=>'m2979/660532f1d12b9',
'skip_auth'=>'1',
],
],
'btn_source_data'=>['aid'=>'6492',
'member_id'=>'2979',
'design_id'=>'7327',
'condition'=>'',
'name'=>'测试',
'role'=>'',
'create_time'=>'2024-04-02 10:41:27',
'status'=>'1',
'is_del'=>'0',
'project_id'=>'0',
'user'=>'',
'type'=>3,
'field_key'=>'',
'field_val'=>'',
'hash'=>'m2979/660532f1d12b9',
'fieldvalue'=>['0'=>['field_key'=>[],
'field_val'=>'',
'fieldJson'=>[],
'dateValueType'=>'0',
'dataShowVal'=>'',
],
],
'system'=>['0'=>['field_key'=>[],
],
],
'table_id'=>'6869',
'url'=>'',
'target'=>'_iframe',
'scan_code'=>'{"table_id":[],"field_id":[]}',
'record'=>'{"table_id":[],"field_id":[]}',
'dept_ids'=>'',
'install_id'=>'0',
'is_batch'=>'0',
'copy_table'=>'0',
'copy_field'=>'',
'copy_source'=>'',
'copy_hash'=>'',
'del_data'=>'0',
'edit_page'=>'0',
'bill_table'=>'0',
'bill_field'=>'',
'add_page'=>'0',
'url_self'=>'',
'set_stock'=>'{"table_id":[],"field_id":[],"type":1,"condition":[]}',
'bind_field'=>'',
'is_right'=>'1',
'top_name'=>'',
'url_type'=>'outer',
'menu_id'=>'0',
'url_bind_column'=>'0',
'remark_field'=>'',
'popup_title'=>'',
'btn_color'=>'rgba(243, 237, 254, 1)',
'is_detail'=>'0',
'detail_name'=>'',
'json_data'=>'{"needSelectRows":true,"btnTheme":"default","btnIcon":"","confirmTitle":""}',
'sort'=>'1',
'location_type'=>'1',
'is_sidebar'=>'1',
'raw_data_id'=>'',
'is_mainadd_colum'=>'1',
],
'type'=>3,
'class'=>'btn btn-xs mr5 btn-default ajax-get confirm',
'extra'=>[],
'del_data'=>'0',
'add_page'=>'0',
'url_self'=>'',
'btn_color'=>'rgba(243, 237, 254, 1)',
'is_source_data'=>'0',
'extend_data'=>'',
'style'=>'color:rgba(243, 237, 254, 1)!important;border-color:rgba(243, 237, 254, 1)!important',
],
'3'=>['btn_id'=>'6493',
'ident'=>'downloadfile',
'title'=>'下载',
'href'=>['0'=>'downloadFiles',
'1'=>['alias'=>'freeinterface',
'layer'=>'1',
'aid'=>'__aid__',
'btn_config_id'=>'6493',
'skip_auth'=>'1',
],
],
'btn_source_data'=>['aid'=>'6493',
'member_id'=>'2979',
'design_id'=>'7327',
'condition'=>'',
'name'=>'下载',
'role'=>'',
'create_time'=>'2024-04-03 15:04:34',
'status'=>'1',
'is_del'=>'0',
'project_id'=>'0',
'user'=>'',
'type'=>7,
'field_key'=>'',
'field_val'=>'',
'hash'=>'',
'fieldvalue'=>['0'=>['field_key'=>[],
'field_val'=>'',
'fieldJson'=>[],
'dateValueType'=>'0',
'dataShowVal'=>'',
],
],
'system'=>['0'=>['field_key'=>[],
],
],
'table_id'=>'6869',
'url'=>'',
'target'=>'_iframe',
'scan_code'=>'{"table_id":[],"field_id":[]}',
'record'=>'{"table_id":[],"field_id":[]}',
'dept_ids'=>'',
'install_id'=>'0',
'is_batch'=>'0',
'copy_table'=>'0',
'copy_field'=>'',
'copy_source'=>'',
'copy_hash'=>'',
'del_data'=>'0',
'edit_page'=>'0',
'bill_table'=>'0',
'bill_field'=>'',
'add_page'=>'0',
'url_self'=>'',
'set_stock'=>'{"table_id":[],"field_id":[],"type":1,"condition":[]}',
'bind_field'=>'',
'is_right'=>'1',
'top_name'=>'',
'url_type'=>'outer',
'menu_id'=>'0',
'url_bind_column'=>'0',
'remark_field'=>'',
'popup_title'=>'',
'btn_color'=>'rgba(5,172,156,1)',
'is_detail'=>'0',
'detail_name'=>'',
'json_data'=>'{"needSelectRows":true,"btnTheme":"default","btnIcon":"","downloadFileName":""}',
'sort'=>'2',
'location_type'=>'1',
'is_sidebar'=>'1',
'raw_data_id'=>'',
'is_mainadd_colum'=>'1',
],
'type'=>7,
'class'=>'btn btn-xs mr5 btn-default ajax-get confirm',
'extra'=>[],
'del_data'=>'0',
'add_page'=>'0',
'url_self'=>'',
'btn_color'=>'rgba(5,172,156,1)',
'is_source_data'=>'0',
'extend_data'=>'',
'style'=>'color:rgba(5,172,156,1)!important;border-color:rgba(5,172,156,1)!important',
],
'4'=>['btn_id'=>'6466',
'ident'=>'verify',
'title'=>'删除',
'href'=>['0'=>'hashApi',
'1'=>['alias'=>'freeinterface',
'layer'=>'1',
'aid'=>'__aid__',
'btn_config_id'=>'6466',
'hash'=>'61a9e69a38658',
'skip_auth'=>'1',
],
],
'btn_source_data'=>['aid'=>'6466',
'member_id'=>'2979',
'design_id'=>'7327',
'condition'=>'',
'name'=>'删除',
'role'=>'',
'create_time'=>'2024-02-05 15:03:13',
'status'=>'1',
'is_del'=>'0',
'project_id'=>'0',
'user'=>'',
'type'=>3,
'field_key'=>'',
'field_val'=>'',
'hash'=>'61a9e69a38658',
'fieldvalue'=>[],
'system'=>'"[{\"field_key\":[]}]"',
'table_id'=>'6869',
'url'=>'',
'target'=>'_iframe',
'scan_code'=>'{"table_id":[],"field_id":[]}',
'record'=>'{"table_id":[],"field_id":[]}',
'dept_ids'=>'',
'install_id'=>'0',
'is_batch'=>'0',
'copy_table'=>'0',
'copy_field'=>'',
'copy_source'=>'',
'copy_hash'=>'',
'del_data'=>'0',
'edit_page'=>'0',
'bill_table'=>'0',
'bill_field'=>'',
'add_page'=>'0',
'url_self'=>'2',
'set_stock'=>'{"table_id":[],"field_id":[],"type":1,"condition":[]}',
'bind_field'=>'',
'is_right'=>'1',
'top_name'=>'',
'url_type'=>'outer',
'menu_id'=>'0',
'url_bind_column'=>'0',
'remark_field'=>'',
'popup_title'=>'',
'btn_color'=>'',
'is_detail'=>'0',
'detail_name'=>'',
'json_data'=>'{"needSelectRows":true,"btnTheme":"default","confirmTitle":"是否确认删除？","btnIcon":""}',
'sort'=>'3',
'location_type'=>'1',
'is_sidebar'=>'1',
'raw_data_id'=>'',
'is_mainadd_colum'=>'1',
],
'type'=>3,
'class'=>'btn btn-xs mr5 btn-default ajax-get confirm',
'extra'=>[],
'del_data'=>'0',
'add_page'=>'0',
'url_self'=>'2',
'btn_color'=>'',
'is_source_data'=>'0',
'extend_data'=>'',
'style'=>'color:!important;border-color:!important',
],
'5'=>['aid'=>'-99999',
'ident'=>'verify',
'title'=>'发起审批',
'href'=>['0'=>null,
'1'=>['alias'=>'freeinterface',
'layer'=>'1',
'id'=>'__aid__',
'launch_id'=>'54',
'tab_id'=>'__tab_id__',
],
],
'class'=>'btn btn-xs mr5 btn-default',
'launch_id'=>'54',
'extra'=>['0'=>['field'=>'approve_status',
'compare'=>'==',
'dataVal'=>'0',
'logic'=>'||',
'fieldType'=>'select',
'index'=>'1',
'extra'=>['0'=>['aid'=>'0',
'name'=>'待发起',
],
'1'=>['aid'=>'1',
'name'=>'通过',
],
'2'=>['aid'=>'2',
'name'=>'拒绝',
],
'3'=>['aid'=>'3',
'name'=>'审核中',
],
'4'=>['aid'=>'4',
'name'=>'已撤销',
],
],
],
'1'=>['field'=>'approve_status',
'compare'=>'==',
'dataVal'=>'',
'logic'=>'||',
'fieldType'=>'select',
'index'=>'1',
'extra'=>['0'=>['aid'=>'0',
'name'=>'待发起',
],
'1'=>['aid'=>'1',
'name'=>'通过',
],
'2'=>['aid'=>'2',
'name'=>'拒绝',
],
'3'=>['aid'=>'3',
'name'=>'审核中',
],
'4'=>['aid'=>'4',
'name'=>'已撤销',
],
],
],
'2'=>['field'=>'approve_status',
'compare'=>'==',
'dataVal'=>'4',
'logic'=>'||',
'fieldType'=>'select',
'index'=>'1',
'extra'=>['0'=>['aid'=>'0',
'name'=>'待发起',
],
'1'=>['aid'=>'1',
'name'=>'通过',
],
'2'=>['aid'=>'2',
'name'=>'拒绝',
],
'3'=>['aid'=>'3',
'name'=>'审核中',
],
'4'=>['aid'=>'4',
'name'=>'已撤销',
],
],
],
'3'=>['field'=>'approve_status',
'compare'=>'==',
'dataVal'=>'2',
'logic'=>'||',
'fieldType'=>'select',
'index'=>'1',
'extra'=>['0'=>['aid'=>'0',
'name'=>'待发起',
],
'1'=>['aid'=>'1',
'name'=>'通过',
],
'2'=>['aid'=>'2',
'name'=>'拒绝',
],
'3'=>['aid'=>'3',
'name'=>'审核中',
],
'4'=>['aid'=>'4',
'name'=>'已撤销',
],
],
],
],
'url_self'=>'1',
'request_fields'=>['alias'=>'__alias__',
'aid'=>'__aid__',
'launch_id'=>'__launch_id__',
'tab_id'=>'__tab_id__',
],
'hash'=>'63535b9b07652',
'btn_type'=>'approve',
],
'6'=>['aid'=>'-99998',
'url_self'=>'1',
'ident'=>'edit',
'title'=>'审批记录',
'href'=>['0'=>null,
'1'=>['table_id'=>'__aid__',
'alias'=>'freeinterface',
'layer'=>'1',
],
],
'class'=>'btn btn-xs mr5 btn-default',
'data-toggle'=>'dialog',
'extra'=>['0'=>['field'=>'approve_status',
'compare'=>'>',
'dataVal'=>'0',
'logic'=>'&&',
'fieldType'=>'select',
'index'=>'1',
'extra'=>['0'=>['aid'=>'0',
'name'=>'待发起',
],
'1'=>['aid'=>'1',
'name'=>'通过',
],
'2'=>['aid'=>'2',
'name'=>'拒绝',
],
'3'=>['aid'=>'3',
'name'=>'审核中',
],
'4'=>['aid'=>'4',
'name'=>'已撤销',
],
],
],
],
'hash'=>'6358cbf03875f',
'request_fields'=>['alias'=>'__alias__',
'table_id'=>'__aid__',
],
'btn_type'=>'record',
],
'7'=>['aid'=>'-99997',
'ident'=>'verify',
'title'=>'撤销审批',
'href'=>['0'=>null,
'1'=>['table_id'=>'__aid__',
'alias'=>'freeinterface',
'approve_status'=>'3',
],
],
'class'=>'btn btn-xs mr5 btn-default ajax-get confirm',
'extra'=>['0'=>['field'=>'approve_status',
'compare'=>'==',
'dataVal'=>'3',
'logic'=>'&&',
'fieldType'=>'select',
'extra'=>['0'=>['aid'=>'0',
'name'=>'待发起',
],
'1'=>['aid'=>'1',
'name'=>'通过',
],
'2'=>['aid'=>'2',
'name'=>'拒绝',
],
'3'=>['aid'=>'3',
'name'=>'审核中',
],
'4'=>['aid'=>'4',
'name'=>'已撤销',
],
],
],
'1'=>['field'=>'create_id',
'compare'=>'==',
'dataVal'=>'25127',
'logic'=>'&&',
'fieldType'=>'text',
'extra'=>[],
],
],
'request_fields'=>['alias'=>'__alias__',
'table_id'=>'__aid__',
],
'hash'=>'636357b923b81',
'btn_type'=>'approve',
],
];

        $top_button = [];
        $btn_show = ['0'=>'1',
'1'=>'2',
'2'=>'4',
'3'=>'6',
'4'=>'9',
'5'=>'7',
'6'=>'8',
];
        foreach ($btn_show as $v){
            $button = $this->button_top[$v];
            if ($button['ident'] == 'add') {
                $button['href'] = '/automatic/m' . MemberID . '.' . $this->module . '/add/tab_id/' . $tab_id;
            }
            $top_button[] = $button;
        }

        foreach ($right_button as $k => &$v) {
            if (isset($v['btn_source_data']['user']) && !empty($v['btn_source_data']['user'])) {
                $right_button[$k]['user'] = $v['btn_source_data']['user'];
            }
            if (isset($v['btn_source_data']['role']) && !empty($v['btn_source_data']['role'])) {
                $right_button[$k]['role'] = $v['btn_source_data']['role'];
            }
            if ($v['ident'] == 'edit') {
                $v['href'][1]['tab_id'] = $tab_id;
            }
        }

        //获取当前用户角色是否可编辑他人数据
        $auth_edit_arr = MemberRole::where('aid', 'in', $roles)->column('auth_edit');
        $user_info = MemberCache::getUserInfoToUserID($member_id, $uid);

        $auth['auth_edit_arr'] = $auth_edit_arr;
        $auth['module'] = $this->module;
        $auth['nickname'] = $user_info['nickname'];

        $right_button = self::checkAuthBtn($right_button, $auth);


        $table = MemberCache::getTableInfoForAlias($member_id,$this->module);

        $where = [
            ['table_id', '=', $table['aid']],
            ['status', '=', 1],
            ['is_del', '=', 0]
        ];
        if ($tab_id) {
            $where[] = ['', 'exp', Db::raw("FIND_IN_SET({$tab_id},tab_ids)")];
        }
        // 导航配置
        $nav_list= FreeNavConfig::where($where)->field('aid,title,is_statistics,nav_json')->select();
        if(count($nav_list) > 0){
            $this->assign('free_tab_nav', $nav_list);
        }

        $this->assign('btn_show', [1]);
        $this->assign('is_statistics', '0');
        $this->assign('top_view', []);
        $this->assign('is_autocode', 1);
        $this->assign('is_hide_checkbox', $this->table['is_hide_checkbox'] ?? 0);
        $this->assign('is_lock', $this->table['is_lock'] ?? 0);
        $this->assign('is_reckon', $this->table['is_reckon'] ?? 0);
        $this->assign('quick_page', $this->table['quick_page'] ?? 0);
        $this->assign('select_table', 0);
        $this->assign('fixed', $this->fixed);
        $this->assign('filter_btn', $this->table['filter_btn'] ?? 1);
        $this->assign('sidebarUrl', "sidebar");
        $this->assign('action_width', $this->table['action_width'] ?? 320);
        $this->assign('list_choose_user_btn', $list_choose_user_btn);
        $this->assign('is_development', 0);
        $this->assign('tab_id', $map['tab_id'] ?? 0);
        $this->assign('member_role',$member_role);

        // 主题色
        $this->assign('theme_set', get_member_config('theme_set'));
        // 是否开启水印
        $this->assign('is_open_watermark', get_member_config('is_open_watermark'));
        // 表格开发模式
        $this->assign('table_js_model', get_member_config('table_js_model') == 1 ? '1' : '');

        return Format::ins()
            ->setPrimaryKey('aid')
            ->setTableName('lb_free_interface')
            ->setIsAdmin(false)
            ->setNotCompileData(false)
            ->setData($data_list)
            ->setpageStatistics($page_statistics)
            ->addColumns($indexFields)
            ->setTopSearch($searchFields)
            ->setTopButtons($top_button)
            ->setRightButtons($right_button)
            ->fetch('spread@public/table-free2');
    }

    // 获取排序字段
    public function getListOrder()
    {
        $order = '';
        $table_info = MemberCache::getTableInfoForAlias(MemberID, $this->module);
        if (!empty($table_info['default_sort'])) {
            $indexFields = FreeProperty::getIndexFields($this->module, 0, "all");
            foreach ($indexFields as $kk => $vv) {
                $new_item[$vv[0]] = $vv[7]['type'];
            }
            $default_sort = json_decode($table_info['default_sort'], true);
            $order = "";
            //条件
            foreach ($default_sort as $key => $val) {
                list($field, $dataVal) = [$val['field'], $val['type']];
                $dataVal = trim($dataVal);
                $type = $new_item[$field];
                if ($type == 'select-table') {
                    $field = preg_replace('/_/', '.', $field, 1);
                    $order .= $field . " " . $dataVal . ",";
                } else {
                    $order .= $this->module . '.' . $field . " " . $dataVal . ",";
                }
            }
            $order = rtrim($order, ",");
        }
        return $order;
    }

    /**
     * 新增
     */
    public function add(){

        //获取当前表名 转小写并拼接表前缀
        $params = $this->request->param();
        $params['alias'] = $this->module;

        if (isset($params['btn_config_id'])) {
            $btn_config_id = $params['btn_config_id'];
        } else {
            $btn_config_id = 0;
        }
        //数据源的按钮ID
        if (isset($params['btn_data_id'])) {
            $btn_data_id = $params['btn_data_id'];
        } else {
            $btn_data_id = 0;
        }
        if (isset($params['rowId'])) {
            $rowId = $params['rowId'];
        } else {
            $rowId = 0;
        }
        if (isset($params['copyAlias'])) {
            $copyAlias = $params['copyAlias'];
        } else {
            $copyAlias = '';
        }
        $table = MemberCache::getTableInfoForAlias(MemberID, $params['alias']);
        $table_name = $table['table_name'];
        config('free_table_name', $table_name);
        $Model = new \app\spread\model\Free();
        $page_title = '新增' . $table['name'];
        $member_id = session("member_auth.member_id") ?: MemberID;
        $member_role = session('member_auth.roles');
        // 保存数据
        if ($this->request->isPost()) {
            try {
                // 套餐验证
                (new BusinessPlan())->check('table_nums', false, [
                    'table' => $table_name
                ]);
            } catch (Exception $exception) {
                $this->error($exception->getMessage());
            }
            // 表单数据
            $param = $this->request->post();
            //是否提交了单据子表数据
            if(isset($param['bill_data'])){
                $bill_data = $param['bill_data'];
                unset($param['bill_data']);
            } else {
                $bill_data = '';
            }
            $table = MemberCache::getTableInfoForAlias($member_id,$this->module);
            $primary_key = $table['primary_key'];
            $manyId = is_manage_many_signin();
            //判断是否是批量添加数据源
            if (!empty($param['is_batch'])) {
                $r_id_name = explode('_', $param['r_id_name']);
                $r_alias = $r_id_name[0];
                $r_id_val = explode(',', $param['r_id_val']);
                $btn_id = $param['btn_id'];
                $data_config = SpreadDataConfig::get($btn_id);
                $btn_data = [];
                SpreadBtnConfig::setRightButton($r_alias, $data_config, $btn_data);
                if (empty($btn_data)) {
                    $this->error('数据源配置错误');
                }
                $r_table = MemberCache::getTableInfoForAlias($member_id,$r_alias);
                $data_list = Db::table($r_table['table_name'])->where($r_table['primary_key'], 'in', $r_id_val)->select();
                //获取当前添加表的字段列表以及获取所有的关联字段
                $table_fields = MemberCache::getFieldListToTableAlias(MemberID,$this->module);
                $r_field_id = [];
                $r_field_link = [];
                foreach ($table_fields as $kk => $vv){
                    if(!empty($vv['r_alias']) && $vv['draw_type'] == 'select-table'){
                        $r_field_id[] = $vv['r_alias'].'_id';
                    }
                    if(!empty($vv['r_alias']) && $vv['draw_type'] == 'select-table-link'){
                        $r_field_link[] = $vv['r_alias'].'_'.$vv['field'];
                    }
                }
                $r_field_id = array_unique($r_field_id);
                $r_field_link = array_unique($r_field_link);
                $r_field_id = array_merge($r_field_id,$r_field_link);
                foreach ($data_list as $val) {
                    // 格式化数据
                    $param[$param['r_id_name']] = $val[$r_table['primary_key']];
                    $data = FreeProperty::handleDataToSave($this->module, $param);
                    // 数据验证
                    $res = \app\spread\validate\Spread::validateData($this->module, $data);
                    if ($res !== true) {
                        $this->error($res);
                    }
                    // 数据来源配置：保存条件
                    if (!SpreadBtnConfig::checkCondition($this->module, $data)) {
                        $this->error('不满足数据来源配置条件');
                    }
                    //给其他关联字段或者联动字段的赋值   两个表都有xxx_id或者相同的联动字段，就把数据给赋值过去
                    foreach ($val as $k => $v){
                        if(in_array($k,$r_field_id) && count($r_field_id) > 0){
                            $data[$k] = $val[$k];
                        }
                    }
                    config('free_table_name', $table_name);
                    $Model = new \app\spread\model\Free();
                    if ($res = $Model->create($data)) {
                        // 数据来源配置：保存后更新
                        $data[$primary_key] = $res[$primary_key];
                        if (!SpreadBtnConfig::afterAdd($this->module, $data,$btn_data_id)) {
                            $this->error('数据来源配置保存后更新失败');
                        }
                        operation_log($table['alias'], $data[$primary_key], MemberUID, '添加了' . $table['name'] . '信息');
                    } else {
                        $this->error('添加失败');
                    }
                }
                $this->success('添加成功', '', ['main_id' => $this->module . '_id', 'main_val' => $data[$primary_key]]);
            } else {
                // 格式化数据
                $data = FreeProperty::handleDataToSave($this->module, $param);
                //如果是合同的数据源按钮，自动生成编码
                if($this->module == 'contract' && isset($data['number']) && empty($data['number'])){
                    $data['number'] = ContractModel::createNo();
                }
                //添加时候判断设置的唯一字段值是否存在
                $all_fields = FreeProperty::getAllFields($this->module);
                foreach ($all_fields as $k => $v) {
                    if ($v['is_unique'] == 1) {
                        if($v['draw_type'] == 'select-table'){
                            $field = $v['r_alias'].'_id';
                        } else {
                            $field = $v['name'];
                        }
                        if(isset($data[$field]) && $data[$field] != ''){
                            $is_cun_data = MapModel::leftJoinObj($this->module)->where([$this->module.'.is_del'=>0,$this->module.'.'.$field=>$data[$field]])->find();
                            if($is_cun_data){
                                $this->error($v['title'].'字段：唯一值已存在！');
                            }
                        }
                    }
                }
                // 新增前 特殊处理
                $c_ret = \app\spread\model\Free::beforeAddHandle($this->module, $data, $member_id);
                if ($c_ret['code'] != 0) {
                    $this->error($c_ret['msg']);
                }
                $data = $c_ret['data'];

                //新增前验证
                $before = SpreadBtnConfig::beforeAddValidate($this->module, $data, $btn_data_id,'add');
                if($before['code'] == 0){
                    $this->error($before['msg']);
                }

                // 数据验证
                $tab_id = $params['tab_id'] ?? 0;
                $res = \app\spread\validate\Spread::validateData($this->module, $data, $tab_id, 'add');
                if ($res !== true) {
                    $this->error($res);
                }
                // 数据来源配置：保存条件
                if (!SpreadBtnConfig::checkCondition($this->module, $data)) {
                    $this->error('不满足数据来源配置条件');
                }
                Db::startTrans();
                try {
                    // 员工表 添加需要单独处理
                    if ($this->module == 'memberuser') {
                        if($data['status'] == 1){
                            $user_count = Db::connect(setMainDbConfig())->table('lb_member_user')->where(["member_id" => $member_id, "status" => 1, "is_del" => 0])->lock(true)->count();
                            $member_info = Db::connect(setMainDbConfig())->table("lb_member")->where(["aid" => $member_id])->find();
                            $chair_number = $member_info["chair_number"];
                            if ($user_count >= $chair_number) {
                                throw new Exception('坐席已满，不能添加员工');
                            }
                        }
                        if (!$data['memberrole_id'] && !$data['roles']) throw new Exception('员工添加必须包含角色');
                        if ($data['memberrole_id'] && !$data['roles']) $data['roles'] = $data['memberrole_id'];
                        $res = User::addUser($data);
                        if (!$res['code']) {
                            throw new Exception($res['msg']);
                        }
                        $res['aid'] = $res['data']['aid'];
                    } else {
                        $res = $Model->create($data);
                    }
                    if (!$res) {
                        throw new Exception('添加失败');
                    }
                    // 处理数据字段多语言写入
                    if (isset($data['lang_arr'])) {
                        $langData = $data;
                        $langData[$params['alias'].'_id'] = $res[$primary_key];
                        $langData['alias'] = $params['alias'];
                        $langData['primary_key'] = $primary_key;
                        \app\spread\model\Free::do_field_lang($langData,$table_name);
                    }
                    // 增加操作记录
                    $is_cus = FreeField::where(['table_name' => $table_name, 'field' => 'customer_id'])->find();
                    // 验证下实际字段是否存在
                    $if_sql = "Describe `{$table_name}` `freekehuguanli_id`;";
                    $if_val = Db::query($if_sql);
                    if ($is_cus || count($if_val) > 0) {
                        $field = $is_cus ? 'customer_id' : 'freekehuguanli_id';
                        $customer_id = Db::table($table_name)->where('aid', $data[$table['primary_key']])->value($field);
                        if (!empty($customer_id)) {
                            addCustomerLog($customer_id, '增加了' . $table['name'] . ' ID：' . $res[$primary_key]);
                        }
                    }
                    operation_log($table['alias'], $data[$primary_key], MemberUID, '添加了' . $table['name'] . '信息');
                    Db::commit();
                } catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                // 数据来源配置：保存后更新
                if (is_array($res) && isset($res[$primary_key])) {
                    $data[$primary_key] = $res[$primary_key];
                } else {
                    $data[$primary_key] = $res->$primary_key;
                }
                $result = SpreadBtnConfig::afterAdd($this->module, $data,$btn_data_id);
                if ((!$result) || (isset($result['code']) && ($result['code'] != 1))) {
                    $this->error(isset($result['msg'])?$result['msg']:'数据来源配置保存后更新失败');
                }
                //数据复制，复制前打开新增页面，处理复制后逻辑
                $copy_res = SpreadBtnConfig::afterCopy($copyAlias, $rowId, $btn_config_id);
                if (!$copy_res) {
                    $this->error('数据来源配置保存后更新失败');
                }

                (new BusinessPlan())->set('table_nums', [
                    'table' => $table_name
                ]);
                //处理单据子表数据增加事务
                Db::startTrans();
                try {
                    //如果单据子表有数据 添加子表数据
                    if ($bill_data) {
                        $saveBillData = \app\spread\model\Free::saveBillData($bill_data, $member_id, $params, $data, $primary_key, $this->module);
                        if ($saveBillData["code"] == 0) {
                            throw new Exception($saveBillData["msg"]);
                        }
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    //失败后更新主表is_del = 1
                    Db::table($table_name)->where('aid',$res['aid'])->update(['is_del'=>1]);
                    $this->error($e->getMessage());
                }

                //循环处理子表事后更新
                if ($bill_data && $saveBillData['code'] == 1) {
                    foreach ($saveBillData['data']['bill_data_sub'] as $k => $v){
                        if (!SpreadBtnConfig::afterAdd($bill_data['alias'], $v)) {
                            return format_data(0, [], '数据来源配置保存后更新失败');
                        }
                        $fa_aids[] = $v['aid'];
                    }
                    //单据子表数据统计
                    if ($bill_data['alias']) {
                        $sub_table = MemberCache::getTableInfoForAlias($member_id, $bill_data['alias']);
                        foreach ($fa_aids as $aid) {
                            $res = FreeFormulaApplyService::handleFormulaApply($sub_table['aid'], '', '', '', $aid, MemberID);
                            if ($res) {
                                FreeFormulaApplyService::handleFormulaData(0, $aid, $sub_table['aid']);
                            }
                        }
                    }
                }
                $this->success('添加成功', '', ['main_id' => $this->module . '_id', 'main_val' => $data[$primary_key]]);
            }
        }

        //查询流程配置信息 当前是否是单据类型
        $is_bill = false;
        $autoSaveField = [];
        $spread = MemberCache::getSpreadInfoForTableID($member_id,$table['aid']);
        // 渲染字段
        $form_items = FreeProperty::getFormFields($this->module, 'add');


        if ($spread && $spread['draw_type'] == 'bill' && $spread['is_dev'] == 0) {
            $is_bill = true;
            //查找子表
            $spreadInfo = SpreadModel::alias('s')->leftJoin('free_table t', ['t.aid=s.table_id'])->where(['s.pid' => $spread['aid'], 's.draw_type' => 'bill', 's.is_del' => 0, 's.status' => 1])->field('s.aid,s.table_id,s.table_name,t.alias,s.spread_id,s.draw_type')->find();
            if (!$spreadInfo) {
                $this->error('流程参数错误3');
            }
            $main_module = $this->module;
            $sub_module = $spreadInfo['alias'];
            $sub_table_info = MemberCache::getTableInfoForAlias($member_id,$sub_module);
            $this->assign('main_alias', $main_module);
            $this->assign('sub_alias', $sub_module);
            $this->assign('sub_table_name', $sub_table_info['table_name']);
            $this->assign('scan_code_json', isset($sub_table_info['scan_code_json']) ? $sub_table_info['scan_code_json'] : '');
            $autoSaveField = ['main_alias' => $main_module, 'sub_alias' => $sub_module];
        }


        //返回字段的分组配置
        $group_list = TableGroup::where('table_id',$table['aid'])->field('aid,name')->order('sort ASC')->select();
        foreach ($group_list as &$v){
            $group_field = FreeField::where('table_group_id',$v['aid'])->column('field_id');
            $v['fields'] = implode(',',$group_field);
        }
        $this->assign('group_list',json_encode($group_list));

        // 重复数据是否可查看详情
        $is_see_repeat_detail_data = MemberConfig::getValueByName('is_see_repeat_detail_data');
        $this->assign('is_see_repeat_detail_data', $is_see_repeat_detail_data);

        //根据视图设置显示添加页面的字段
        if (isset($params['tab_id']) && $params['tab_id'] != 0) {
            $tabConfigInfo = FreeTabConfig::where(['aid' => $params['tab_id']])->find();
            if(!empty($tabConfigInfo['add_column'])){
                $add_column = json_decode($tabConfigInfo['add_column']);
                foreach ($form_items as $key => $item) {
                    if(!in_array($item['name'],$add_column)){
                        unset($form_items[$key]);
                    }
                }
            }
            //是否开启条件为添加默认值
            if($tabConfigInfo['is_add_default'] == 1){
                $condition = json_decode($tabConfigInfo['condition'],true);
                foreach ($condition as $kk1 => $vv1){
                    $condit[$vv1['field']] = $vv1['dataVal'];
                }
                foreach ($form_items as $kk => $vv){
                    if(isset($condit[$vv['name']])){
                        $form_items[$kk]['value'] = $condit[$vv['name']];
                    }
                }
            }
            //如果是视图，查询和视图关联的查询条件
            $select_condition = $tabConfigInfo['select_condition'];
            if(!empty($select_condition)){
                $select_condition = json_decode($select_condition,true);
                foreach ($select_condition as $k => $v){
                    $new_condition[$v['field_id']][] = $v;
                }
                foreach ($form_items as &$val) {
                    $val['condition'] = json_encode($new_condition[$val['field_id']]);
                }
            }
        }
        $this->assign('member_role',$member_role);

        $form_items = [
["type"=>"diydate","name"=>"riqixuanzeqi","field_id"=>129110,"unit"=>"","title"=>"日期选择器","tips"=>"","lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null,"date_format"=>"HH:mm"],
["type"=>"number","name"=>"shuzi","field_id"=>129093,"unit"=>"","title"=>"数字","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"image","name"=>"tupian1","field_id"=>129097,"unit"=>"","title"=>"图片1","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"image","name"=>"tupian2","field_id"=>129098,"unit"=>"","title"=>"图片2","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"video","name"=>"shipin1","field_id"=>129083,"unit"=>"","title"=>"视频1","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"select-table","name"=>"freegenerateinterface_shoujihao","field_id"=>129095,"unit"=>"","title"=>"手机号","index_url"=>"/spread/free/index/field_id/129095/alias/freegenerateinterface","tips"=>"","extra"=>null,"condition"=>"","lang"=>[],"is_edit"=>0,"is_required"=>0,"table_name"=>"lb_free_generate_interface","alias"=>"freegenerateinterface","r_alias"=>"freegenerateinterface","original_draw_type"=>"mobile","value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null,"select_table_multiple"=>0,"select_table_checkbox"=>0,"checkbox_value"=>0],
["type"=>"text","name"=>"shoujihao_2","field_id"=>129096,"unit"=>"","title"=>"手机号2","tips"=>"","lang"=>[],"is_edit"=>0,"is_required"=>0,"table_name"=>"lb_free_generate_interface","alias"=>"freeinterface","r_alias"=>"freegenerateinterface","original_draw_type"=>"mobile","value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null],
["type"=>"files","name"=>"wenjian","field_id"=>129084,"unit"=>"","title"=>"文件","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"system","name"=>"xitongyuangong","field_id"=>129057,"unit"=>"","title"=>"系统员工","tips"=>"","extra"=>[["aid"=>384,"name"=>"总公司","child"=>[["aid"=>386,"name"=>"市场部","child"=>[["aid"=>52355,"name"=>"张无忌"]]],["aid"=>385,"name"=>"销售部","child"=>[["aid"=>396,"name"=>"123","child"=>[["aid"=>399,"name"=>"218部门","child"=>[]],["aid"=>401,"name"=>"218部门2","child"=>[]]]]]],["aid"=>389,"name"=>"财务部","child"=>[]],["aid"=>25127,"name"=>"李迪开发"]]]],"lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>25127,"decimal_places"=>0,"dept_type"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null],
["type"=>"images","name"=>"duotu","field_id"=>129068,"unit"=>"","title"=>"多图","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"link","name"=>"lianjie","field_id"=>129056,"unit"=>"","title"=>"链接","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"code","name"=>"bianma","field_id"=>128887,"unit"=>"","title"=>"编码","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"text","name"=>"free_field_129071","field_id"=>129071,"unit"=>"","title"=>"使用微信数","tips"=>"","lang"=>[],"is_edit"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null],
["type"=>"text","name"=>"weixin","field_id"=>128954,"unit"=>"","title"=>"微信","tips"=>"","extra"=>null,"lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null,"json_data"=>"","regexp"=>""],
["type"=>"address","name"=>"shengshiqu","field_id"=>128922,"unit"=>"","title"=>"省市区","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"select-table","name"=>"freeform_gongsimingcheng","field_id"=>129047,"unit"=>"","title"=>"公司名称","index_url"=>"/spread/free/index/field_id/129047/alias/freeform","tips"=>"","extra"=>null,"condition"=>"","lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_form_","alias"=>"freeform","r_alias"=>"freeform","original_draw_type"=>"text","value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null,"select_table_multiple"=>0,"select_table_checkbox"=>0,"checkbox_value"=>0],
["type"=>"money","name"=>"qiankuanjine","field_id"=>129048,"unit"=>"","title"=>"欠款金额","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"0","decimal_places"=>2,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"select","name"=>"xuanxiang","field_id"=>129050,"unit"=>"","title"=>"选项","tips"=>"","extra"=>[["name"=>"一","index"=>"0","aid"=>"1","is_default"=>"0"],["name"=>"二","index"=>"1","aid"=>"2","is_default"=>"0"],["name"=>"三","index"=>"2","aid"=>"3","is_default"=>"0"],["name"=>"四","index"=>"3","aid"=>"4","is_default"=>"0"],["name"=>"五","index"=>"4","aid"=>"5","is_default"=>"0"]],"lang"=>[],"is_edit"=>1,"is_required"=>1,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null,"json_data"=>"","regexp"=>""],
["type"=>"text","name"=>"cheng","field_id"=>128862,"unit"=>"","title"=>"昵称","tips"=>"","extra"=>null,"lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null,"json_data"=>"","regexp"=>""],
["type"=>"mobile","name"=>"shoujihao","field_id"=>128921,"unit"=>"","title"=>"手机号","tips"=>"","extra"=>null,"lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null,"json_data"=>"","regexp"=>""],
["type"=>"dept","name"=>"bumen","field_id"=>128886,"unit"=>"","title"=>"部门","tips"=>"","extra"=>[["aid"=>384,"name"=>"总公司","child"=>[["aid"=>386,"name"=>"市场部"],["aid"=>385,"name"=>"销售部","child"=>[["aid"=>396,"name"=>"123","child"=>[["aid"=>399,"name"=>"218部门"],["aid"=>401,"name"=>"218部门2"]]]]],["aid"=>389,"name"=>"财务部"]]]],"lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>384,"decimal_places"=>0,"dept_type"=>1,"fields_description"=>"","show_roles"=>"","edit_roles"=>null],
["type"=>"users","name"=>"yuangong","field_id"=>128885,"unit"=>"","title"=>"员工","tips"=>"","extra"=>[["aid"=>384,"name"=>"总公司","pid"=>0,"child"=>[["aid"=>386,"name"=>"市场部","pid"=>384,"child"=>[["aid"=>52355,"name"=>"张无忌","roles"=>"491","pid"=>386]]],["aid"=>389,"name"=>"财务部","pid"=>384,"child"=>[]],["aid"=>25127,"name"=>"李迪开发","roles"=>"1","pid"=>384]]]],"lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>25127,"decimal_places"=>0,"dept_type"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null],
["type"=>"map","name"=>"dituxuandian","field_id"=>128923,"unit"=>"","title"=>"地图选点","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"files","name"=>"wenjianshangchuan","field_id"=>128884,"unit"=>"","title"=>"文件上传","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>"",'json_data' =>"{\"filesVerify\":\"\",\"isCheckedverify\":\"0\",\"maxUploadCount\":\"1\"}"],
["type"=>"image","name"=>"touxiang","field_id"=>128874,"unit"=>"","title"=>"头像","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"video","name"=>"shipin","field_id"=>128881,"unit"=>"","title"=>"视频","tips"=>"","lang"=>[],"is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>null,"address_level"=>0,"hj_field"=>null,'video_config' =>"{\"video_speed\":\"1\",\"video_times\":\"1\",\"video_hash\":\"\"}"],
["type"=>"text","name"=>"free_field_128868","field_id"=>128868,"unit"=>"","title"=>"订单使用次数","tips"=>"","lang"=>[],"is_edit"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null],
["type"=>"text","name"=>"free_field_128870","field_id"=>128870,"unit"=>"","title"=>"手机使用次数","tips"=>"","lang"=>[],"is_edit"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null],
["type"=>"date","name"=>"shengri","field_id"=>128863,"unit"=>"","title"=>"生日","tips"=>"","lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null,"date_format"=>0],
["type"=>"select","name"=>"xingbie","field_id"=>128864,"unit"=>"","title"=>"性别","tips"=>"","extra"=>[["name"=>"男","index"=>"0","aid"=>"1","is_default"=>"0"],["name"=>"女","index"=>"1","aid"=>"2","is_default"=>"0"],["name"=>"保密","index"=>"2","aid"=>"3","is_default"=>"0"]],"lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null,"json_data"=>"","regexp"=>""],
["type"=>"selects","name"=>"aihao","field_id"=>128865,"unit"=>"","title"=>"爱好","tips"=>"","extra"=>[["name"=>"唱","index"=>"0","aid"=>"1","is_default"=>"0"],["name"=>"跳","index"=>"1","aid"=>"2","is_default"=>"0"],["name"=>"rap","index"=>"2","aid"=>"3","is_default"=>"0"],["name"=>"篮球","index"=>"3","aid"=>"4","is_default"=>"0"]],"lang"=>[],"is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>null,"json_data"=>"","regexp"=>""],
];

        foreach ($form_items as $key => $val) {
            //字段根据角色判断是否限制
            if (!in_array(1, $this->roles) && $val['edit_roles']) {
                $check_roles = explode(',', $val['edit_roles']);

                if (!array_intersect($this->roles, $check_roles)) {
                    unset($form_items[$key]);
                    continue;
                }
            }
        }
        $this->assign('form_items', array_values($form_items));

        //判断是否是单据类型 渲染页面不一样
        if ($is_bill) {
            $indexFields = FreeProperty::getIndexFields($sub_module);
            //过滤掉添加不显示的字段
            foreach ($indexFields as $kk => $vv){
                if($vv[7]['is_add_draw'] == 0){
                    unset($indexFields[$kk]);
                }
            }
            $indexFields = array_values($indexFields);
            //初始化已有选项和已有表格
            $this->handleFreeProperty($sub_module);
            //初始化统计信息
            $this->getCensusList($sub_module);

            // 全部部门列表
            $dept_list = \app\member\model\MemberDept::getDeptListAll();
            $this->assign('dept_list', $dept_list);
            // 全部角色列表
            $role_list = MemberCache::getMemberRoleTree($member_id);
            $this->assign('role_list', $role_list);

            // 自定义流程-显示配置-按钮配置
            $btn_show = SpreadBtnConfig::btnShow($sub_module);
            $this->assign('btn_show', $btn_show);

            // 子表自定义流程-显示配置-按钮配置
            $bill_btn_show = SpreadBtnConfig::btnShow($sub_module);
            $this->assign('bill_btn_show', $bill_btn_show);

            // 查询是否配置[改变所属]自定义按钮
            $list_choose_user_btn = SpreadBtnConfig::getBatchChooseUserBtn($sub_module);
            $this->assign('list_choose_user_btn', $list_choose_user_btn);

            // 数据源批量自定义按钮
            $list_batch_data_btn = SpreadBtnConfig::getBatchDataBtn($sub_module);
            $this->assign('list_batch_data_btn', $list_batch_data_btn);
            //如果$autoSaveField是null的时候 则转为空数组
            if (empty($autoSaveField)) {
                $autoSaveField = [];
            }
            $this->assign('autoSaveField', $autoSaveField);
            $this->assign('is_admin', 0);
            $this->assign('table_add_not_show', 0);
            //默认view模板
            $temp = 'spread@public/add-bill';
            return Format::ins()
                ->setPrimaryKey('aid')
                ->setPageTitle($page_title)
                ->setIsAdmin(false)
                ->setData($data_list)
                ->addColumns($indexFields)
                ->setNotCompileData(true)
                ->fetch($temp);
        } else {
            $this->handleFreeProperty($this->module);//加载自定义属性和表格
            $this->assign('page_title', $page_title);
            return $this->fetch('spread@public/act_form');
        }


    }

    /**
     * 编辑
     * @param null $id 接口id
     */
    public function edit($id = null){
        if ($id === null) {
            $this->error('缺少参数');
        }

        //获取当前表名 转小写并拼接表前缀
        $params = $this->request->param();
        if (empty($params['alias'])) {
            $this->error('参数错误');
        }

        $table = MemberCache::getTableInfoForAlias(MemberID, $params['alias']);
        $table_name = $table['table_name'];
        config('free_table_name', $table_name);
        $Model = new \app\spread\model\Free();
        $page_title = '编辑' . $table['name'];
        $member_role = session('member_auth.roles');
        $member_id = session("member_auth.member_id") ?: MemberID;

        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $param = $this->request->post();
            //是否提交了单据子表数据
            if(isset($param['bill_data'])){
                $bill_data = $param['bill_data'];
                unset($param['bill_data']);
            }else{
                $bill_data = '';
            }

            $tab_id = $params['tab_id'] ?? 0;

            // 格式化数据
            $data = FreeProperty::handleDataToSave($this->module, $param);

            // 数据验证
            $res = \app\spread\validate\Spread::validateData($this->module, $data,$tab_id,'edit');
            if ($res !== true) {
                $this->error($res);
            }

            // 数据来源配置：保存条件
            if (!SpreadBtnConfig::checkCondition($this->module, $data)) {
                $this->error('不满足数据来源配置条件');
            }

            // 旧数据
            $old_data = $Model->where($table['primary_key'], $data[$table['primary_key']])->find();

            //新增前验证
            $before = SpreadBtnConfig::beforeAddValidate($this->module, $data, 0,'edit');
            if($before['code'] == 0){
                $this->error($before['msg']);
            }

            $upwhere = [];
            $upwhere[] = [$table['primary_key'], '=', $data[$table['primary_key']]];
            $upwhere = manage_many_find_where($upwhere,2);

            if (!$res = $Model::where($upwhere)->find()) $this->error('数据未找到');
            Db::startTrans();
            try {
                $res = $Model::update($data);
                if(!$res){
                    throw new Exception('编辑失败');
                }

                // 处理数据字段多语言写入
                $data['alias'] = $params['alias'];
                $data['primary_key'] = $table['primary_key'];
                if (isset($data['lang_arr'])) \app\spread\model\Free::do_field_lang($data,$table_name);
                // 增加操作记录
                $is_cus = FreeField::where(['table_name' => $table_name, 'field' => 'customer_id'])->find();
                if ($is_cus) {
                    $customer_id = $Model::where('aid', $data[$table['primary_key']])->value('customer_id');
                    if ($customer_id) {
                        addCustomerLog($customer_id, '增加了' . $table['name'] . ' ID：' . $table['primary_key']);
                    }
                }
                // 对边变更数据
                $changeData = comparison_data_change($table_name, $old_data, $data);
                operation_log($table['alias'], $data[$table['primary_key']], MemberUID, '编辑了' . $table['name'] . '信息', json_encode($changeData));

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            // 数据来源配置：保存后更新
            $result = SpreadBtnConfig::afterEdit($this->module, $data, $old_data);
            if (!$result) {
                $this->error('数据来源配置保存后更新失败');
            }

            //开启单据子表数据处理事务
            Db::startTrans();
            try {
                //如果单据子表有数据 添加子表数据
                if ($bill_data) {
                    $saveBillData = \app\spread\model\Free::saveBillData($bill_data, $member_id, $params, $data, $table['primary_key'], $this->module);
                    if ($saveBillData["code"] == 0) {
                        throw new Exception($saveBillData["msg"]);
                    }
                }
            Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            //循环处理子表事后更新
            if ($bill_data && $saveBillData['code'] == 1) {
                $sub_table = MemberCache::getTableInfoForAlias($member_id, $bill_data['alias']);
                //单据详情表调取编辑后更新
                foreach ($saveBillData['data']['old_data'] as $k => $v){
                    if (!SpreadBtnConfig::afterEdit($bill_data['alias'], $saveBillData['data']['bill_data_sub'][$k],$v)) {
                        throw new Exception('数据来源配置保存后更新失败');
                    }
                    $fa_aids[] = $v['aid'];
                }
                //单据子表数据统计
                if ($bill_data['alias']) {
                    foreach ($fa_aids as $aid) {
                        $res = FreeFormulaApplyService::handleFormulaApply($sub_table['aid'], '', '', '', $aid, MemberID);
                        if ($res) {
                            FreeFormulaApplyService::handleFormulaData(0, $aid, $sub_table['aid']);
                        }
                    }
                }
            }
            $this->success('编辑成功', '', ['main_id' => $this->module . '_id', 'main_val' => $data[$table['primary_key']]]);
        }

        //查询流程配置信息 当前是否是单据类型
        $is_bill = false;
        $spread = MemberCache::getSpreadInfoForTableAlias(MemberID, $table['alias']);
        if ($spread && $spread['draw_type'] == 'bill' && $spread['is_dev'] == 0) {
            $is_bill = true;
            //查找子表
            $spreadInfo = SpreadModel::alias('s')->leftJoin('free_table t', ['t.aid=s.table_id'])->where(['s.pid' => $spread['aid'], 's.draw_type' => 'bill', 's.is_del' => 0, 's.status' => 1])->field('s.aid,s.table_id,s.table_name,t.alias,s.spread_id,s.draw_type,t.primary_key')->find();
            if (!$spreadInfo) {
                $this->error('流程参数错误3');
            }
            $main_module = $this->module;
            $sub_module = $spreadInfo['alias'];
            $spread_pk = $spreadInfo['primary_key'];
            //获取子表详情
            $sub_table = MemberCache::getTableInfoForAlias(MemberID,$sub_module);
            $this->assign('is_development', $sub_table['is_development']);
            $this->assign('main_alias', $main_module);
            // 单据子表表头统计
            $this->assign('autoSearchField', [$main_module . '_id' => $id]);
            $this->assign('sub_alias', $sub_module);
            $this->assign('sub_table_name', $sub_table['table_name']);
            $this->assign('scan_code_json', isset($sub_table_info['scan_code_json']) ? $sub_table_info['scan_code_json'] : '');
            $autoSaveField = ['main_alias' => $main_module, 'sub_alias' => $sub_module];
            $this->assign('autoSaveField', $autoSaveField);
        }

        // 详细信息
        $data = FreeinterfaceModel::leftJoinObj($this->module)->where($this->module . '.aid', $id)->find() ?: [];
        $data2 = Db::table($table_name)->where(aid, '=', $id)->where('is_del', '=', 0)->find() ?: [];
        $data = $data + $data2;
        if (!$data) {
            $this->error('数据或已被删除', cookie('__forward__'));
        }

        //查询字段
        $form_items = [
["type"=>"diydate","name"=>"riqixuanzeqi","field_id"=>129110,"unit"=>"","title"=>"日期选择器","tips"=>"","lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>"","date_format"=>"HH:mm"],
["type"=>"number","name"=>"shuzi","field_id"=>129093,"unit"=>"","title"=>"数字","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"image","name"=>"tupian1","field_id"=>129097,"unit"=>"","title"=>"图片1","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"image","name"=>"tupian2","field_id"=>129098,"unit"=>"","title"=>"图片2","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"video","name"=>"shipin1","field_id"=>129083,"unit"=>"","title"=>"视频1","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"select-table","name"=>"freegenerateinterface_shoujihao","field_id"=>129095,"unit"=>"","title"=>"手机号","index_url"=>"/spread/free/index/field_id/129095/alias/freegenerateinterface","tips"=>"","extra"=>null,"condition"=>"","lang"=>"","is_edit"=>0,"is_required"=>0,"table_name"=>"lb_free_generate_interface","alias"=>"freegenerateinterface","r_alias"=>"freegenerateinterface","original_draw_type"=>"mobile","value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>"","select_table_multiple"=>0,"select_table_checkbox"=>0,"checkbox_value"=>0],
["type"=>"text","name"=>"shoujihao_2","field_id"=>129096,"unit"=>"","title"=>"手机号2","tips"=>"","lang"=>"","is_edit"=>0,"is_required"=>0,"table_name"=>"lb_free_generate_interface","alias"=>"freeinterface","r_alias"=>"freegenerateinterface","original_draw_type"=>"mobile","value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>""],
["type"=>"files","name"=>"wenjian","field_id"=>129084,"unit"=>"","title"=>"文件","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"system","name"=>"xitongyuangong","field_id"=>129057,"unit"=>"","title"=>"系统员工","tips"=>"","extra"=>[["aid"=>384,"name"=>"总公司","child"=>[["aid"=>386,"name"=>"市场部","child"=>[["aid"=>52355,"name"=>"张无忌"]]],["aid"=>385,"name"=>"销售部","child"=>[["aid"=>396,"name"=>"123","child"=>[["aid"=>399,"name"=>"218部门","child"=>[]],["aid"=>401,"name"=>"218部门2","child"=>[]]]]]],["aid"=>389,"name"=>"财务部","child"=>[]],["aid"=>25127,"name"=>"李迪开发"]]]],"lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"dept_type"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>""],
["type"=>"images","name"=>"duotu","field_id"=>129068,"unit"=>"","title"=>"多图","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"link","name"=>"lianjie","field_id"=>129056,"unit"=>"","title"=>"链接","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"code","name"=>"bianma","field_id"=>128887,"unit"=>"","title"=>"编码","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"text","name"=>"free_field_129071","field_id"=>129071,"unit"=>"","title"=>"使用微信数","tips"=>"","lang"=>"","is_edit"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>""],
["type"=>"text","name"=>"weixin","field_id"=>128954,"unit"=>"","title"=>"微信","tips"=>"","extra"=>null,"lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>"","json_data"=>"","regexp"=>""],
["type"=>"address","name"=>"shengshiqu","field_id"=>128922,"unit"=>"","title"=>"省市区","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"select-table","name"=>"freeform_gongsimingcheng","field_id"=>129047,"unit"=>"","title"=>"公司名称","index_url"=>"/spread/free/index/field_id/129047/alias/freeform","tips"=>"","extra"=>null,"condition"=>"","lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_form_","alias"=>"freeform","r_alias"=>"freeform","original_draw_type"=>"text","value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>"","select_table_multiple"=>0,"select_table_checkbox"=>0,"checkbox_value"=>0],
["type"=>"money","name"=>"qiankuanjine","field_id"=>129048,"unit"=>"","title"=>"欠款金额","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"0","decimal_places"=>2,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"select","name"=>"xuanxiang","field_id"=>129050,"unit"=>"","title"=>"选项","tips"=>"","extra"=>[["name"=>"一","index"=>"0","aid"=>"1","is_default"=>"0"],["name"=>"二","index"=>"1","aid"=>"2","is_default"=>"0"],["name"=>"三","index"=>"2","aid"=>"3","is_default"=>"0"],["name"=>"四","index"=>"3","aid"=>"4","is_default"=>"0"],["name"=>"五","index"=>"4","aid"=>"5","is_default"=>"0"]],"lang"=>"","is_edit"=>1,"is_required"=>1,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>"","json_data"=>"","regexp"=>""],
["type"=>"text","name"=>"cheng","field_id"=>128862,"unit"=>"","title"=>"昵称","tips"=>"","extra"=>null,"lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>"-1","json_data"=>"","regexp"=>""],
["type"=>"mobile","name"=>"shoujihao","field_id"=>128921,"unit"=>"","title"=>"手机号","tips"=>"","extra"=>null,"lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>"","json_data"=>"","regexp"=>""],
["type"=>"dept","name"=>"bumen","field_id"=>128886,"unit"=>"","title"=>"部门","tips"=>"","extra"=>[["aid"=>384,"name"=>"总公司","child"=>[["aid"=>386,"name"=>"市场部"],["aid"=>385,"name"=>"销售部","child"=>[["aid"=>396,"name"=>"123","child"=>[["aid"=>399,"name"=>"218部门"],["aid"=>401,"name"=>"218部门2"]]]]],["aid"=>389,"name"=>"财务部"]]]],"lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>384,"decimal_places"=>0,"dept_type"=>1,"fields_description"=>"","show_roles"=>"","edit_roles"=>""],
["type"=>"users","name"=>"yuangong","field_id"=>128885,"unit"=>"","title"=>"员工","tips"=>"","extra"=>[["aid"=>384,"name"=>"总公司","pid"=>0,"child"=>[["aid"=>386,"name"=>"市场部","pid"=>384,"child"=>[["aid"=>52355,"name"=>"张无忌","roles"=>"491","pid"=>386]]],["aid"=>389,"name"=>"财务部","pid"=>384,"child"=>[]],["aid"=>25127,"name"=>"李迪开发","roles"=>"1","pid"=>384]]]],"lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"dept_type"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>""],
["type"=>"map","name"=>"dituxuandian","field_id"=>128923,"unit"=>"","title"=>"地图选点","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"files","name"=>"wenjianshangchuan","field_id"=>128884,"unit"=>"","title"=>"文件上传","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>"",'json_data' =>"{\"filesVerify\":\"\",\"isCheckedverify\":\"0\",\"maxUploadCount\":\"1\"}"],
["type"=>"image","name"=>"touxiang","field_id"=>128874,"unit"=>"","title"=>"头像","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,"video_config"=>""],
["type"=>"video","name"=>"shipin","field_id"=>128881,"unit"=>"","title"=>"视频","tips"=>"","lang"=>"","is_edit"=>1,"is_cut"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"json_data"=>"","fields_description"=>"","max"=>null,"min"=>null,"show_roles"=>"","edit_roles"=>"","address_level"=>0,"hj_field"=>null,'video_config' =>"{\"video_speed\":\"1\",\"video_times\":\"1\",\"video_hash\":\"\"}"],
["type"=>"text","name"=>"free_field_128868","field_id"=>128868,"unit"=>"","title"=>"订单使用次数","tips"=>"","lang"=>"","is_edit"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>""],
["type"=>"text","name"=>"free_field_128870","field_id"=>128870,"unit"=>"","title"=>"手机使用次数","tips"=>"","lang"=>"","is_edit"=>0,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>""],
["type"=>"date","name"=>"shengri","field_id"=>128863,"unit"=>"","title"=>"生日","tips"=>"","lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>"","date_format"=>0],
["type"=>"select","name"=>"xingbie","field_id"=>128864,"unit"=>"","title"=>"性别","tips"=>"","extra"=>[["name"=>"男","index"=>"0","aid"=>"1","is_default"=>"0"],["name"=>"女","index"=>"1","aid"=>"2","is_default"=>"0"],["name"=>"保密","index"=>"2","aid"=>"3","is_default"=>"0"]],"lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>"","json_data"=>"","regexp"=>""],
["type"=>"selects","name"=>"aihao","field_id"=>128865,"unit"=>"","title"=>"爱好","tips"=>"","extra"=>[["name"=>"唱","index"=>"0","aid"=>"1","is_default"=>"0"],["name"=>"跳","index"=>"1","aid"=>"2","is_default"=>"0"],["name"=>"rap","index"=>"2","aid"=>"3","is_default"=>"0"],["name"=>"篮球","index"=>"3","aid"=>"4","is_default"=>"0"]],"lang"=>"","is_edit"=>1,"is_required"=>0,"table_name"=>"lb_free_interface","alias"=>"freeinterface","r_alias"=>"","original_draw_type"=>null,"value"=>"","decimal_places"=>0,"fields_description"=>"","show_roles"=>"","edit_roles"=>"","json_data"=>"","regexp"=>""],
];
        $form_items[] = ['type' => 'hidden', 'name' => 'aid', 'value' => $id];
        foreach ($form_items as $key => $val) {
            //字段根据角色判断是否限制
            if (!in_array(1, $this->roles) && $val['edit_roles']) {
            $check_roles = explode(',', $val['edit_roles']);

            if (!array_intersect($this->roles, $check_roles)) {
                unset($form_items[$key]);
                continue;
                }
            }
        }

        // 格式化数据
        $data = FreeProperty::handleDataToShow($this->module, $data, $data_type = 1, $is_statistics = 0, $is_app = 0, $is_address = 0, $is_export = 1);

        //详情模式查看 不可编辑数据
        if ($params['show_detail'] == 1) {
            $this->assign('btn_hide', 1);
            $page_title = '查看' . $table['name'];
        }

        foreach ($form_items as $key => $val) {
            //详情模式查看 不可编辑数据
            if ($params['show_detail'] == 1) {
                $form_items[$key]['is_edit'] = 0;
            }
            if ($val['type'] == 'select-table') {
                $r_id = $val['alias'] . '_id';
                $form_items[$key]['rid'] = $data[$r_id];
            }
        }

        //根据视图设置显示添加页面的字段
        if (isset($params['tab_id']) && $params['tab_id'] != 0) {
            $tabConfigInfo = FreeTabConfig::where(['aid' => $params['tab_id']])->find();
            if(!empty($tabConfigInfo['edit_column'])){
                $edit_column = json_decode($tabConfigInfo['edit_column']);
                foreach ($form_items as $key => $item) {
                    if (!in_array($item['name'], $edit_column) && $item['name'] != 'aid') {
                        unset($form_items[$key]);
                    }
                }
            }
            //视图单独处理字段排序
            if(!empty($tabConfigInfo['sort_fields'])){
                $sort_fields = json_decode($tabConfigInfo['sort_fields'],true);
                foreach ($form_items as $k => $v) {
                    $form_items[$k]['sort'] = $sort_fields[$v['field_id']];
                }
                $form_items = \app\spread\model\Free::arraySort($form_items,'sort','asc');
                $form_items = array_values($form_items);
            }
            //如果是视图，查询和视图关联的查询条件
            $select_condition = $tabConfigInfo['select_condition'];
            if(!empty($select_condition)){
                $select_condition = json_decode($select_condition,true);
                foreach ($select_condition as $k => $v){
                    $new_condition[$v['field_id']][] = $v;
                }
                foreach ($form_items as &$val) {
                    $val['condition'] = json_encode($new_condition[$val['field_id']]);
                }
            }
        }

        $form_items = array_values($form_items);
        $form_items = $this->setData($form_items, $data);
        foreach ($form_items as &$from_field) {
            if(!empty($from_field['hj_field'])){
                $from_field['is_edit'] = 0;
            }
            $from_field['title'] = lang($from_field['title']);
            if ($from_field['extra']) {
                foreach ($from_field['extra'] as &$item) {
                    $item['name'] = lang($item['name']);
                    if (isset($item['child'])) {
                        foreach ($item['child'] as &$val) {
                            $val['name'] = lang($val['name']);
                        }
                    }
                }
            }
            // 增加字段数据翻译语种字段
            if (isset($from_field['lang']) && $from_field['lang']) {
                $from_field['lang'] = FreeProperty::get_field_lang($from_field,'edit',$id);
            }
            //如果是关联字段为真实值，特殊处理返回的name
            if($from_field['type'] == 'select-table-value'){
                $from_field['name'] = $from_field['r_alias'].'_'.$from_field['select_table_field'];
            }
        }

        unset($from_field);
        $form_items = hidden_account_info_table($form_items,1);
        $this->assign('form_items', $form_items);
        $this->assign('aid', $id);
        $this->assign('member_role',$member_role);

        //返回字段的分组配置
        $group_list = TableGroup::where('table_id',$table['aid'])->field('aid,name')->order('sort ASC')->select();
        foreach ($group_list as &$v){
            $group_field = FreeField::where('table_group_id',$v['aid'])->column('field_id');
            $v['fields'] = implode(',',$group_field);
        }
        $this->assign('group_list',json_encode($group_list));

        // 重复数据是否可查看详情
        $is_see_repeat_detail_data = MemberConfig::getValueByName('is_see_repeat_detail_data');
        $this->assign('is_see_repeat_detail_data', $is_see_repeat_detail_data);

        // 数据验重是否可查看详情
        $this->assign('is_see_repeat_detail_data', get_member_config('is_see_repeat_detail_data'));

        //判断是否是单据类型，单据类型单独页面样式
        if ($is_bill) {
            //渲染子表和数据
            $where = [];
            $where[] = [$sub_module . '.' . $main_module . '_id', '=', $id];
            //根据配置单据详情是否分页
            //$sub_table = MemberCache::getTableInfoForTableID(MemberID,$spreadInfo['table_id']);
            $sub_table = FreeTable::where('aid',$spreadInfo['table_id'])->find();
            $group = empty($spread_pk) ? $sub_module . '.' . "aid" : $sub_module . '.' . $spread_pk;

            //子表排序
            $sub_order = "";
            $sub_module_info = MemberCache::getTableInfoForAlias(MemberID, $sub_module);
            if (!empty($sub_module_info['default_sort'])) {
                $subIndexFields = FreeProperty::getIndexFields($sub_module, 0, "all");
                foreach ($subIndexFields as $kk => $vv) {
                    $new_item[$vv[0]] = $vv[7]['type'];
                }
                $default_sort = json_decode($sub_module_info['default_sort'], true);
                //条件
                foreach ($default_sort as $key => $val) {
                    list($field, $dataVal) = [$val['field'], $val['type']];
                    $dataVal = trim($dataVal);
                    $type = $new_item[$field];
                    if ($type == 'select-table') {
                        $field = preg_replace('/_/', '.', $field, 1);
                        $sub_order .= $field . " " . $dataVal . ",";
                    } else {
                        $sub_order .= $sub_module . '.' . $field . " " . $dataVal . ",";
                    }
                }
                $sub_order = rtrim($sub_order, ",");
            }
            if (empty($sub_order)){
                $sub_order = $sub_module . ".sort ASC," . $sub_module . ".aid DESC";
            }
            if($sub_table['is_bill_page'] == 1){
                $list_rows = MemberCache::getDefaultPage($sub_module, session('member_auth.member_id') ,$params['list_rows']);
                $data_list = MapModel::leftJoinObj($sub_module)->where($where)->group($group)->order($sub_order)->paginate($list_rows);   //加了分页
            } else {
                $data_list = MapModel::leftJoinObj($sub_module)->where($where)->group($group)->order($sub_order)->select();
            }
            foreach ($data_list as $key => $data1) {
                $data_list[$key] = FreeProperty::handleDataToShow($sub_module, $data1);
            }
            $indexFields = FreeProperty::getIndexFields($sub_module);
            //过滤掉编辑不显示的字段
            foreach ($indexFields as $kk => $vv){
                if($vv[7]['is_edit_draw'] == 0){
                    unset($indexFields[$kk]);
                }
            }
            $indexFields = array_values($indexFields);
            //根据视图配置显示单据子表的字段
            if (isset($params['tab_id']) && $params['tab_id'] != 0) {
                $tabConfigInfo = FreeTabConfig::where(['aid' => $params['tab_id']])->find();
                if(!empty($tabConfigInfo['bill_field_column'])){
                    $bill_field_column = json_decode($tabConfigInfo['bill_field_column']);
                    foreach ($indexFields as $kl => $iteml) {
                        if(!in_array($iteml[0],$bill_field_column)){
                            unset($indexFields[$kl]);
                        }
                    }
                    $indexFields = array_values($indexFields);
                }
            }
            //初始化已有选项和已有表格
            $this->handleFreeProperty($sub_module);
            //初始化统计信息
            $this->getCensusList($sub_module);

            // 全部部门列表
            $dept_list = MemberCache::getDeptTree(MemberID);
            $this->assign('dept_list', $dept_list);
            // 全部角色列表
            $role_list = MemberCache::getMemberRoleTree(MemberID);
            $this->assign('role_list', $role_list);

            // 子表自定义流程-显示配置-按钮配置
            $bill_btn_show = SpreadBtnConfig::btnShow($sub_module);
            $this->assign('bill_btn_show', $bill_btn_show);

            // 查询是否配置[改变所属]自定义按钮
            $list_choose_user_btn = SpreadBtnConfig::getBatchChooseUserBtn($sub_module);
            foreach ($list_choose_user_btn as $kk => $subBtn){
                if($subBtn['is_mainadd_colum'] == 0){   //编辑时，判断单据子表顶部的自定义按钮是否显示
                    unset($list_choose_user_btn[$kk]);
                }
            }
            $this->assign('list_choose_user_btn', array_values($list_choose_user_btn));

            // 数据源批量自定义按钮
            $list_batch_data_btn = SpreadBtnConfig::getBatchDataBtn($sub_module);
            $this->assign('list_batch_data_btn', $list_batch_data_btn);

            //详情模式查看 不可编辑数据
            if ($params['show_detail'] == 1) {
                $this->assign('is_development', 0);
            }
            //默认view模板
            $temp = 'spread@public/add-bill';
            return Format::ins()
                ->setPrimaryKey('aid')
                ->setPageTitle($page_title)
                ->setIsAdmin(false)
                ->setData($data_list)
                ->addColumns($indexFields)
                ->setNotCompileData(true)
                ->fetch($temp);
        } else {
            // 全部部门列表
            $dept_list = MemberCache::getDeptTree(MemberID);
            $this->assign('dept_list', $dept_list);
            $this->handleFreeProperty($this->module);//加载自定义属性和表格

            $this->assign('page_title', $page_title);
            return $this->fetch('spread@public/act_form');
        }
    }

    /**
    * 详情
    * @param null $id 接口id
    */
    public function detail($id = null){
        if ($id === null) {
            $this->error('缺少参数');
        }

        $params = $this->request->param();
        //$table = FreeTable::where('alias', $params['alias'])->find();
        $table = MemberCache::getTableInfoForAlias(MemberID,$this->module);
        $table_name = $table['table_name'];
        config('free_table_name', $table_name);
        $Model = new \app\spread\model\Free();
        $page_title = '编辑' . $table['name'];

        //查询流程配置信息 当前是否是单据类型
        $is_bill = false;
        //$spread = SpreadModel::where(['table_id' => $table['aid']])->find();
        $spread = MemberCache::getSpreadInfoForTableID(MemberID,$table['aid']);
        if ($spread && $spread['draw_type'] == 'bill' && $spread['is_dev'] == 0) {
            $is_bill = true;
            //查找子表
            $spreadInfo = SpreadModel::alias('s')->leftJoin('free_table t', ['t.aid=s.table_id'])->where(['s.pid' => $spread['aid'], 's.draw_type' => 'bill', 's.is_del' => 0, 's.status' => 1])->field('s.aid,s.table_id,s.table_name,t.alias,s.spread_id,s.draw_type')->find();
            if (!$spreadInfo) {
                $this->error('流程参数错误3');
            }
            $main_module = $this->module;
            $sub_module = $spreadInfo['alias'];
            $this->assign('main_alias', $main_module);
            $this->assign('sub_alias', $sub_module);
            $autoSaveField = ['main_alias' => $main_module, 'sub_alias' => $sub_module];
            $this->assign('autoSaveField', $autoSaveField);
        }

        // 详细信息
        $data2 = [];
        $data = MapModel::leftJoinObj($this->module)->where($this->module . '.' . $table['primary_key'], $id)->find() ?: [];
        // 使用权限验证数据，有权限看再补全字段
        if($data) {
            $data2 = Db::table($table_name)->where($table['primary_key'], '=', $id)->where('is_del', '=', 0)->find() ?: [];
        }
        $data = $data + $data2;
        if (!$data) {
            $this->error('数据不存在或无权限', cookie('__forward__'));
        }
        // 格式化数据
        $data = FreeProperty::handleDataToShow($this->module, $data);
        //查询字段
        $form_items = FreeProperty::getFormFields($this->module, 'detail');
        //根据视图设置显示详情页面的字段
        if (isset($params['tab_id']) && $params['tab_id'] != 0) {
            $tabConfigInfo = FreeTabConfig::where(['aid' => $params['tab_id'], 'alias'=>$this->module])->find();

            if(!empty($tabConfigInfo['pc_detail_column']) && $tabConfigInfo['pc_detail_column'] != '[]'){
                $pc_detail_column = json_decode($tabConfigInfo['pc_detail_column']);
                $form_items = FreeProperty::getFormFields($this->module, 'detail',1);
                foreach ($form_items as $key => $item) {
                    if(!in_array($item['name'],$pc_detail_column)){
                        unset($form_items[$key]);
                    }
                }
            }
            $form_items = array_values($form_items);
        }
        $form_items[] = ['type' => 'hidden', 'name' => $table['primary_key'], 'value' => $id];
        foreach ($form_items as $key => $val) {
            //详情模式查看 不可编辑数据
            if ($params['show_detail'] == 1) {
                $form_items[$key]['is_edit'] = 0;
            }
            if ($val['type'] == 'select-table') {
                $r_id = $val['alias'] . '_id';
                $form_items[$key]['rid'] = $data[$r_id];
            }
        }

        //详情模式查看 不可编辑数据
        if ($params['show_detail'] == 1) {
            $this->assign('btn_hide', 1);
            $page_title = '查看' . $table['name'];
        }
        //表单数据渲染到页面
        $form_items = $this->setData($form_items, $data);
        $group_list = TableGroup::where('table_id',$table['aid'])->field('aid,name')->select();
        foreach ($group_list as &$v){
            $group_field = FreeField::where('table_group_id',$v['aid'])->column('field_id');
            $v['fields'] = implode(',',$group_field);
        }
        $this->assign('group_list',json_encode($group_list));

        $this->assign('form_items', $form_items);
        $this->assign('aid', $id);

        //判断是否是单据类型，单据类型单独页面样式
        if ($is_bill) {
            //渲染子表和数据
            $where = [];
            $where[] = [$sub_module . '.' . $main_module . '_id', '=', $id];
            $data_list = MapModel::leftJoinObj($sub_module)->where($where)->order($sub_module . ".sort ASC,".$sub_module.".aid DESC")->paginate();
            foreach ($data_list as $key => $data1) {
                $data_list[$key] = FreeProperty::handleDataToShow($sub_module, $data1);
            }
            $indexFields = FreeProperty::getIndexFields($sub_module);
            //初始化已有选项和已有表格
            $this->handleFreeProperty($sub_module);
            //初始化统计信息
            $this->getCensusList($sub_module);

            // 全部部门列表
            $dept_list = MemberCache::getDeptTree(MemberID);
            $this->assign('dept_list', $dept_list);
            // 全部角色列表
            $role_list = MemberCache::getMemberRoleTree(MemberID);
            $this->assign('role_list', $role_list);

            // 自定义流程-显示配置-按钮配置
            $btn_show = SpreadBtnConfig::btnShow($this->module);
            $this->assign('btn_show', $btn_show);

            // 查询是否配置[改变所属]自定义按钮
            $list_choose_user_btn = SpreadBtnConfig::getBatchChooseUserBtn($this->module);
            $this->assign('list_choose_user_btn', $list_choose_user_btn);

            // 数据源批量自定义按钮
            $list_batch_data_btn = SpreadBtnConfig::getBatchDataBtn($this->module);
            $this->assign('list_batch_data_btn', $list_batch_data_btn);

            //详情模式查看 不可编辑数据
            if ($params['show_detail'] == 1) {
                $this->assign('is_development', 0);
            }
            //默认view模板
            $temp = 'spread@public/add-bill';
            return Format::ins()
                ->setPrimaryKey('aid')
                ->setPageTitle($page_title)
                ->setIsAdmin(false)
                ->setData($data_list)
                ->addColumns($indexFields)
                ->setNotCompileData(true)
                ->fetch($temp);
        } else {
            // 全部部门列表
            $dept_list = MemberCache::getDeptTree(MemberID);
            $this->assign('dept_list', $dept_list);
            $this->handleFreeProperty($this->module);//加载自定义属性和表格

            $this->assign('page_title', $page_title);
            return $this->fetch('spread@public/act_form');
        }
    }


    /**
    * 侧边栏
    * @param null $id 接口id
    */
    public function sidebar()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $params = $this->request->param();
        $aid = $params['id'] ?:$params['aid']; // 当前数据的主键ID
        if (!$aid) $this->error('数据ID不能为空');

        $free_table = MemberCache::getTableInfoForAlias(MemberID, $this->module);
        if (!$free_table) {
            $this->error('请检查数据表是否存在');
        }
        //检测当前列表是否可打开详情页（free_table_config中有没有当前列表的配置）
        $is_has_config = FreeTableConfig::where(['table_id'=>$free_table['aid']])->find();
        if(empty($is_has_config)){
            $spread = MemberCache::getSpreadInfoForTableID(MemberID,$free_table['aid']);
            $tableConfig = [
                'member_id'=>MemberID,
                'table_id'=>$free_table['aid'],
                'spread_id'=>$spread['aid'],
                'sidebar_ids'=>json_encode([$free_table['aid']=>'99']),
                'sidebar_name'=>json_encode([$free_table['aid']=>$free_table['name'].'详情']),
            ];
            FreeTableConfig::create($tableConfig);
            MemberCache::setTableConfigInfoToCache(MemberID, $free_table['aid'], 'table_id');
        }else{
            if(empty($is_has_config['sidebar_name']) || empty($is_has_config['sidebar_ids'])){
                $tableConfig = [
                    'sidebar_ids'=>json_encode([$free_table['aid']=>'99']),
                    'sidebar_name'=>json_encode([$free_table['aid']=>$free_table['name'].'详情']),
                ];
                FreeTableConfig::where(['aid'=>$is_has_config['aid']])->update($tableConfig);
                // MemberCache::setTableConfigListToCache(MemberID);
                MemberCache::setTableConfigInfoToCache(MemberID, $free_table['aid'], 'table_id');
            }
        }
        //详情页显示按钮
        $right_button = SpreadModel::getRightButtonByAuth($this->module,[],$params['tab_id'],1);
        foreach ($right_button as $k => $v) {
            if(!isset($v['btn_id']) || $v['btn_source_data']['is_detail'] == 0){
                unset($right_button[$k]);
            }else{
                $right_button[$k]['title'] = $v['btn_source_data']['detail_name'] ?: $v['title'];
            }
        }
        $right_button = array_values($right_button);
        $this->assign('right_button',json_encode($right_button));

        // 获取要显示当前模块详情的view_config
        $where = [
            ['member_id', '=', MemberID],
            ['', 'exp', Db::raw("FIND_IN_SET({$free_table['aid']},siderbar)")],
            // ['menu','=',1],
        ];
        //        $list_view = SpreadViewConfig::where($where)->select()->toArray();
        $list_view = [];
        // 循环处理
        foreach ($list_view as $key => $val) {
            $spread_id = $val['design_id'];
            $spread_info = MemberCache::getSpreadInfoForSpreadID(MemberID, $spread_id);
            $table_id = $spread_info['table_id'];

            $free_table_view = MemberCache::getTableInfoForTableID(MemberID, $table_id);
            if ($free_table_view) {
                $free_table_view = $free_table_view->toArray();

                $draw_type = $spread_info['draw_type'];
                if ($draw_type == 'form') {
                    $vars = [
                        'alias' => $free_table_view['alias'],
                        'r_id_name' => $free_table['alias'] . '_id',
                        'r_id_val' => $aid,
                        'layer' => 1,
                        'sidebar' => 1
                    ];
                    $free_table_view['index_url'] = url('spread/free/add', $vars);
                } else {
                    $vars = [
                        'layer' => 1,
                        'sidebar' => 1,
                        'alias' => $free_table_view['alias'],
                        'r_id_name' => $free_table['alias'] . '_id',
                        'r_id_val' => $aid,
                    ];
                    $free_table_view['index_url'] = url('spread/free/index', $vars);
                }

                // 详情导航栏名字
                $siderbar_name = json_decode($val['siderbar_name'], true);
                if ($siderbar_name[$free_table['aid']]) {
                    $free_table_view['name'] = $siderbar_name[$free_table['aid']];
                }

                $list[] = $free_table_view;
            }
        }

        // 关联表设置显示在sidebar中
        $table_config = MemberCache::getTableConfigInfoToID(MemberID, $free_table['aid']);
        $sidebar_ids = $table_config['sidebar_ids'];
        $sidebar_url = $table_config['sidebar_url'];
        $sidebar_name = $table_config['sidebar_name'];
        if ($sidebar_url) {
            $_sidebar_url = json_decode($sidebar_url, true);
            if ($_sidebar_url) {
                $sidebar_url = $_sidebar_url;
            } else {
                $_sidebar_url = explode(',', $sidebar_url);
                $sidebar_url = array_flip($_sidebar_url);
            }
        }
        if ($sidebar_name) {
            $_sidebar_name = json_decode($sidebar_name, true);
            if ($_sidebar_name) {
                $sidebar_name = $_sidebar_name;
            } else {
                $_sidebar_name = explode(',', $sidebar_name);
                $sidebar_name = array_flip($_sidebar_name);
            }
        }
        $relist = [];
        if ($sidebar_ids) {
            $_sidebar = json_decode($sidebar_ids, true);

            if ($_sidebar) {
                $sidebar_idss = [];
                foreach ($_sidebar as $items => $val) {
                    $sidebar_idss[] = $items;
                }
            } else {
                $sidebar_idss = explode(',', $sidebar_ids);
            }

            // 获取当前用户的权限
            $menu_auth = model('member/member_role')->roleAuth();
            // 查看用户角色
            $uid = session('member_auth.uid') ?: MemberUID;
            $user_info = User::where('aid', $uid)->find();
            $role_str = $user_info->roles;
            $role_arr = explode(',', $role_str);

            foreach ($sidebar_idss as $key => $val) {
                $spread_info = MemberCache::getSpreadInfoForTableID(MemberID, $val);
                $draw_type = $spread_info['draw_type'];
                $spread_id = $spread_info['aid'];
                $table_id = $val;

                $free_table_view = MemberCache::getTableInfoForTableID(MemberID, $table_id);
                if (!$free_table_view) {
                    continue;
                }

                // 获取菜单id，查看权限是否存在，不存在去除
                if($free_table_view['alias'] == 'receivable' || $free_table_view['alias'] == 'customer' ||$free_table_view['alias'] == 'contract'){
                    $url_value = 'crm/'.$free_table_view['alias'].'/index';
                }else{
                    $url_value = 'spread/free/index?alias=' . $free_table_view['alias'];
                }

                $menu_ids = MemberMenu::where('member_id', 'in', [0, MemberID])->where(['status' => 1])->where('url_value', 'like', $url_value . '%')->column('aid');

                $is_role = false;
                foreach ($menu_ids as $menu_id) {
                    if (isset($menu_auth[$menu_id])) {
                        $is_role = true;
                    }
                }

                if (!in_array('1', $role_arr) && $is_role == false) {
                    unset($sidebar_idss[$key]);
                    continue;
                }
                $vars = [
                    'alias' => $free_table_view['alias'],
                    'r_id_name' => $free_table['alias'] . '_id',
                    'r_id_val' => $aid,
                    'layer' => 1,
                ];
                foreach ($params as $keyData => $valData){
                    if(strpos($keyData, '_id') !== false && $valData != '' && $keyData != 'tab_id'){
                        $vars[$keyData] = $valData;
                    }
                }
                if ($draw_type == 'record') {
                    $seas_status = 1;
                    if (is_customer_table($free_table['table_name'])) {
                        $version_1 = $free_table['table_name'] == 'lb_crm_customer';
                        if ($version_1) {
                            $c_ret = Db::table($free_table['table_name'])->where('aid', $aid)->where('status', 2)->find();
                        } else {
                            $val = RuleVersionConst::getFreePropertyVal();
                            $c_ret = Db::table($free_table['table_name'])->where('aid', $aid)->where('shifougonghai', $val['seas_val_yes'])->find();
                        }
                        if ($c_ret) {
                            $seas_status = 2;
                        }
                    }

                    $vars['use_new_record'] = 1;
                    $vars['sidebar'] = 1;
                    // 记录公海状态 1客户列表 2公海
                    $vars['seas_status'] = $seas_status;
                }
                else if ($draw_type == 'formtable') {
                    //表单表格
                    $vars['use_formtable'] = 1;
                    $vars['sidebar'] = 1;
                }
                else if ($draw_type == 'formrecord') {
                    //表单 沟通记录
                    $vars['use_formrecord'] = 1;
                    $vars['sidebar'] = 1;
                }
                else {
                    $vars['sidebar'] = 1;
                }

                if($free_table_view['alias'] == 'receivable' || $free_table_view['alias'] == 'customer' ||$free_table_view['alias'] == 'contract'){
                    $free_table_view['index_url'] = url($url_value, $vars);
                }else{
                    $free_table_view['index_url'] = url('spread/free/index', $vars);
                }

                if ($draw_type == 'form') {
                    $alias_key = $free_table['alias'] . '_id';
                    //检验下数据库中是否存在这个字段
                    //验证下实际字段是否存在
                    $if_sql = "Describe `{$spread_info['table_name']}` `{$alias_key}`;";
                    $if_val = Db::query($if_sql);
                    if (count($if_val) > 0) {
                        $data = Db::table($spread_info['table_name'])->where($free_table['alias'] . '_id', '=', $aid)->where(['is_del' => 0, 'status' => 1])->order('aid asc')->find();
                        if ($data) {
                            unset($vars['r_id_name']);
                            unset($vars['r_id_val']);
                            $vars['id'] = $data['aid'];

                            $form_url_value = 'spread/free/edit?alias='.$vars['alias'];
                            $form_menu_ids = MemberMenu::where('member_id', 'in', [0, MemberID])->where(['status' => 1])->where('url_value', 'like', $form_url_value . '%')->column('aid');
                            $is_role_form = false;
                            foreach ($form_menu_ids as $form_menu_id) {
                                if (isset($menu_auth[$form_menu_id])) {
                                    $is_role_form = true;
                                }
                            }
                            if (!in_array('1', $role_arr) && $is_role_form == false) {
                                $vars['show_detail'] = 1;
                                $free_table_view['index_url'] = url('spread/free/detail', $vars);
                            }else{
                                $free_table_view['index_url'] = url('spread/free/edit', $vars);
                            }

                        } else {
                            $free_table_view['index_url'] = url('spread/free/add', $vars);
                        }
                    }
                }


                // 详情导航栏名字
                $siderbar_name = json_decode($val['siderbar_name'], true);
                if ($siderbar_name[$free_table['aid']]) {
                    $free_table_view['name'] = $siderbar_name[$free_table['aid']];
                }

                $list[$table_id] = $free_table_view;
            }
            //重新排序
            asort($_sidebar);
            foreach ($_sidebar as $k => $v) {
                if (isset($list[$k])) {
                    $relist[] = $list[$k];
                }
            }
        }

        $free_table['index_url'] = url('spread/free/detail', ['alias' => $free_table['alias'], 'id' => $aid, 'layer' => 1, 'sidebar' => 1, 'show_detail' => 1,'tab_id'=>$params['tab_id'] ?? 0]);
        $index_url = url('detail', ['alias' => $free_table['alias'], 'id' => $aid, 'layer' => 1, 'sidebar' => 1, 'show_detail' => 1,'tab_id'=>$params['tab_id'] ?? 0]);
        // 关联模块
        if ($relist) {
            //array_unshift($relist, $free_table);
            foreach ($relist as &$v) {
                if ($v['aid'] == $free_table['aid']) {
                    $v['name'] = $free_table['name'] . '详情';
                    $v['index_url'] = $index_url;
                }
                if($sidebar_url[$v['aid']] != ''){
                    unset($vars['alias']);
                    //如果是外链，不拼接参数
                    if (strpos($sidebar_url[$v['aid']], 'http') !== false || strpos($sidebar_url[$v['aid']], 'https') !== false || strpos($sidebar_url[$v['aid']], '//') !== false) {
                        $v['index_url'] = $sidebar_url[$v['aid']];
                    }else{
                        $varss = [
                            'r_id_name' => $free_table['alias'] . '_id',
                            'r_id_val' => $aid,
                            'layer' => 1,
                            'sidebar' => 1,
                        ];
                        $v['index_url'] = url($sidebar_url[$v['aid']], $varss);
                    }

                }
                if($sidebar_name[$v['aid']] != ''){
                    $v['name'] = $sidebar_name[$v['aid']];
                }
            }
        }

        $fields = Db::table($free_table['table_name'])->getTableFields();
        $data = Db::table($free_table['table_name'])->where($free_table['primary_key'], $aid)->find();
        if (in_array('approve_status',$fields) && $data['approve_status'] !== 0) {
            $relist[] = array(
                'name' => '审核记录',
                'alias' => 'approvelog',
                'sort' => 99,
                'index_url' => url('spread/approve/approvelog',['table_id'=>$aid,'alias'=>$params['alias']]),
            );
        }

        // 如果是客户管理，加入操作日志
        if ($params['alias'] == 'freekehuguanli') {
            CustomerLog::addLog($aid, '查看了客户', 7);
            $arr = array(
                'name' => '操作记录',
                'alias' => 'customerlog',
                'sort' => 99,
                'index_url' => url('crm/customer/get_log_new', ['id' => $aid]),
            );
            $relist[] = $arr;
        }
        //整理自带关联侧边栏的sort字段
        $relist = json_decode(json_encode($relist),true);
        foreach ($relist as $kv => $vl){
            if(isset($_sidebar[$vl['aid']])){
                $relist[$kv]['sort'] = $_sidebar[$vl['aid']];
            }
            if ($relist[$kv]['name']) $relist[$kv]['name'] = lang($vl['name']);
        }

        //自定义侧边栏
        $sidebar_list = FreeTableSidebar::where(['is_del'=>0,'status'=>1,'table_id'=>$free_table['aid']])->order('sort ASC')->select();
        foreach ($sidebar_list as $kv => $vl){
            $relation_table = MemberCache::getTableInfoForTableID(MemberID,$vl['relation_tableId']);
            $current_table = MemberCache::getTableInfoForTableID(MemberID,$vl['table_id']);
            $condition = json_decode($vl['condition'],true);
            $current_field_str = '';
            $where_str = [];
            foreach ($condition as $key => $value) {
                if($value['type'] == 1){
                    $where_str[] = [
                        $relation_table['alias'] . '_' . $value['field']=>$value['current_field'],
                    ];
                }else{
                    $current_field_str .= $value['current_field'].',';
                }
            }
            $current_field_str = substr_replace($current_field_str,"",-1);
            $data_str = Db::table($current_table['table_name'])->where($current_table['primary_key'],$aid)->field($current_field_str)->find();
            $vars_str = [];
            //条件为字段的，拼接条件时值与减更换
            foreach ($condition as $k1 => $va) {
                if($va['type'] == 0){
                    $vars_str[$va['field']] = $data_str[$va['current_field']];
                }
            }
            $vars_str_arr = [];
            foreach ($vars_str as $kl => $vk){
                if (strpos($kl, '_id') !== false) {
                    $vars_str_arr['r_id_name'] = $kl;
                    $vars_str_arr['r_id_val'] = $vk;
                }else{
                    $vars_str_arr['r_id_name'] = $relation_table['alias'].'_'.$kl;
                    $vars_str_arr['r_id_val'] = $vk;
                    //$vars_str_arr[$kl] = $vk;
                }
            }
            $vars = [
                'layer' => 1,
                'sidebar' => 1,
                'is_role' => $vl['is_role'],
                'alias' => $relation_table['alias'],
            ];
            if(!empty($current_field_str) && count($vars_str_arr) > 0){
                $vars = array_merge($vars,$vars_str_arr);
            }
            if(count($where_str) > 0){
                foreach ($where_str as $kk => $vv) {
                    $vars = array_merge($vars,$vv);
                }
            }
            //新数组
            $relation['aid'] = 'free_'.$vl['aid'];
            $relation['name'] = lang($vl['name']);
            $relation['sort'] = $vl['sort'];
            $relation['alias'] = $relation_table['alias'];
            //如果有自定义链接，则不再匹配
            if(!empty($vl['url_value'])){
                //如果是外链，不拼接参数
                if(strpos($vl['url_value'], 'wage') !== false){
                    $menu_idss = MemberMenu::where('member_id', 'in', [0, MemberID])->where(['status' => 1])->where('url_value', 'like', $vl['url_value'] . '%')->column('aid');
                    $is_has_role = false;
                    foreach ($menu_idss as $menu_ids) {
                        if (isset($menu_auth[$menu_ids])) {
                            $is_has_role = true;
                        }
                    }
                    if (!in_array('1', $role_arr) && $is_has_role == false) {
                        unset($sidebar_list[$kv]);
                        continue;
                    }
                }
                if (strpos($vl['url_value'], 'http') !== false || strpos($vl['url_value'], 'https') !== false || strpos($vl['url_value'], '//') !== false) {
                    $relation['index_url'] = $vl['url_value'];
                }else{
                    $relation['index_url'] = url($vl['url_value'], $vars);
                }
            }else{
                $url_value = 'spread/free/index?alias='.$vars['alias'];
                $menu_idss = MemberMenu::where('member_id', 'in', [0, MemberID])->where(['status' => 1])->where('url_value', 'like', $url_value . '%')->column('aid');
                $is_has_role = false;
                foreach ($menu_idss as $menu_ids) {
                    if (isset($menu_auth[$menu_ids])) {
                        $is_has_role = true;
                    }
                }
                if (!in_array('1', $role_arr) && $is_has_role == false) {
                    unset($sidebar_list[$kv]);
                    continue;
                }

                $free_table = MemberCache::getTableInfoForAlias(MemberID, $vars['alias']);

                if ($free_table && $free_table['is_autocode'] == 1) {
                    $uri = '/automatic/m' . MemberID . '.' . $vars['alias'] . '/index';
                    foreach ($vars as $k => $v) {
                        $uri .= '/' . $k . '/' . $v;
                    }
                    $uri .= '.html';
                    $relation['index_url'] = $uri;
                } else {
                    $relation['index_url'] = url('spread/free/index', $vars);
                }
            }
            $relist[] = $relation;
        }
        //根据sort字段排序
        $relist = \app\spread\model\Free::arraySort($relist,'sort','asc');
        //根据视图显示侧边栏
        if(isset($params['tab_id']) && $params['tab_id']){
            $disabled_sidebar = FreeTabConfig::where('aid',$params['tab_id'])->value('disabled_sidebar');
            $disabled_sidebar = json_decode($disabled_sidebar);
            foreach ($relist as $kl => $vk){
                if(in_array($vk['aid'],$disabled_sidebar)){
                    unset($relist[$kl]);
                }
            }
        }
        $relist = array_values($relist);
        $this->assign('pm_list', $relist);
        $this->assign('aid', $aid);

        //读取第1个页面
        $this->assign('show_alias', $relist[0]['alias']);
        $this->assign('member_role',session('member_auth.roles'));
        return $this->fetch('spread@public/sidebar');
    }

    //设置状态
    public function setStatus($type)
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        $field = input('param.field', 'status');
        if (empty($type)) {
            $type = input('param.action');
        }

        empty($ids) && $this->error('缺少主键');

        $Model = new FreeinterfaceModel();
        // 主键名称
        $pk = $Model->getPk() ?? 'aid';
        $result = false;
        switch ($type) {
            case 'disable': // 禁用
                $result = $Model->where($pk, 'IN', $ids)->setField($field, 0);
                break;
            case 'enable': // 启用
                $result = $Model->where($pk, 'IN', $ids)->setField($field, 1);
                break;
            case 'delete': // 删除
                $result = $Model->where($pk, 'IN', $ids)->setField('is_del', 1);
                break;
            default:
                $this->error('非法操作');
                break;
        }

        $table = strtolower(str_replace('__', '', $Model->getTable()));
        if (false !== $result) {
            // 记录行为
            action_log($table . '_' . $type, $table, $ids, 0, 'ID：' . implode('、', $ids));
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }


    /**
     * 改变状态
     * @author ligeliang
     * @date 2021-10-08 9:47
     */
    public function changeStatus()
    {
        $param = $this->request->param();

        $alias = $param['alias'];
        $ids = $param['id'];
        if(empty($ids)){
            $ids = isset($param['aid'])? $param['aid']:'';
        }
        if (!$ids) {
            $this->error('参数错误');
        }
        $param_ids = $ids;
        $btn_config_id = $param['btn_config_id'];

        $table = FreeTable::where('alias', $alias)->find();
        $primary_key = $table['primary_key'];
        $table_name = $table['table_name'];


        // 配置值
        $btn_config = SpreadBtnConfig::where('aid', $btn_config_id)->find();
        if (!$btn_config) {
            $this->error('配置不存在');
        }

        $fieldvalue = json_decode($btn_config['fieldvalue'], true);
        foreach ($fieldvalue as $key => $val) {
            if ($val['fieldType'] == 'date' || $val['fieldType'] == 'datetime') {
                $data[$val['field_key']] = time();
            } elseif($val['fieldType'] == 'year' || $val['fieldType'] == 'month' || $val['fieldType'] == 'day' || $val['fieldType'] == 'time'){
                switch ($val['fieldType']) {
                    case 'year':
                        $data[$val['field_key']] = strtotime($val['field_val'] . '-01-01 00:00:00');
                        break;
                    default:
                        $data[$val['field_key']] = strtotime($val['field_val']);
                        break;
                }
            } else{
                $data[$val['field_key']] = $val['field_val'] == 'ACTION_TIME' ? time() : $val['field_val'];
            }
            if($val['fieldType'] == 'address' || $val['fieldType'] == 'select-multiple'){
                $data[$val['field_key']] = implode(',',$val['field_val']);
            }
        }
        $data['update_time'] = time();
        if(isset($param['remark_field']) && $param['remark_field'] != 0){
            $field_info = MemberCache::getFieldInfoToFieldID(MemberID,$param['remark_field']);
            if ($field_info['is_null'] == 1 && !trim($param['remark'])) {
                $this->error('备注不能为空');
            }
            $data[$field_info['field']] = $param['remark'];
        }

        // $res = $Model->where('aid', 'in', $ids)->update($data);
        $ids = is_array($ids) ? $ids : explode(',', $ids);
        foreach ($ids as $key => $id) {
            config('free_table_name', $table_name);
            $Model = new \app\spread\model\Free();
            if ($primary_key == 'aid') {
                $data['aid'] = $id;
                $res = $Model::update($data);
            } else {
                $data[$primary_key] = $id;
                $res = $Model::update($data, [$primary_key => $id]);
            }

            // 改变后更新
            if (!SpreadBtnConfig::afterChange($param['alias'], $id, $btn_config_id)) {
                $this->error('改变状态后更新失败');
            }
        }
        if ($res !== false) {
            // 更新单行数据
            $line_data = MapModel::leftJoinObj($this->module)->where($this->module . '.' . $primary_key, 'in', $ids)->find() ?: [];
            $raw_data = Db::table($table_name)->where($primary_key, 'in', $ids)->where('is_del', '=', 0)->find() ?: [];
            $line_data = $line_data + $raw_data;
            $line_data = FreeProperty::handleDataToShow($this->module, $line_data);

            if($this->module == 'customer'){
            $line_data['status'] = $line_data['status'] == 1 ? '否' : ($line_data['status'] == 2 ? '是' : '未确认');
            }

            // 增加操作记录
            try {
                if (is_customer_table($table_name)) {
                    $field = 'aid';
                } else {
                    $field = 'customer_id';
                }
                $customer_id = Db::table($table_name)->where('aid', $data[$table['primary_key']])->value($field);
                if ($customer_id) {
                    foreach ($ids as $id) {
                        addCustomerLog($id, '操作了' . $btn_config['name'] . '按钮');
                    }
                }
            } catch (\Exception $e) {
                // todo nothing
            }
            operation_log($alias, $param_ids, MemberUID, '操作了 ' . $btn_config['name'] . '按钮');
            $this->success('操作成功', '', $line_data);
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 自定义hash接口
     * @author ligeliang
     * @date 2021-12-02 15:21
     */
    public function hashApi()
    {
        $param = $this->request->param();

        $alias = $param['alias'];
        $ids = $param['ids'];
        $btn_config_id = $param['btn_config_id'];
        //$hash = $param['hash'];
        $btn_config = SpreadBtnConfig::where('aid', $btn_config_id)->field('hash,name')->find();
        /*addons_action("RabbitMQ", "Hook", "send", [
            \app\spread\server\SpreadApiTask::class,//流程设计中的API消费
            "run",//执行SQL方法名
            ['hash' => $btn_config['hash'], 'alias' => $alias, 'aid' => $ids, 'member_id' => MemberID, 'member_uid' => MemberUID], //参数,当前表别名和当前新增或变更的数据ID
            Env::get('QUEUE.SPAPI_QUEUE', 'spapi_queue')  //队列通道
        ]);*/
        //更换接口执行方式
        $res = \app\spread\server\SpreadApiTask::executeApi(['hash' => $btn_config['hash'], 'alias' => $alias, 'aid' => $ids, 'member_id' => MemberID, 'member_uid' => MemberUID]);
        operation_log($alias, $ids, MemberUID, '操作了 ' . $btn_config['name'].'按钮');
        $this->success('操作成功',null,$res);
    }
    /**
     * 选择员工
     * @author ligeliang
     * @date 2021-10-08 9:25
     */
    public function choseUser()
    {
        if ($this->request->isPost()) {
            $param = $this->request->post();
            if (empty($param['id'])) {
                $this->error('缺少参数');
            }
            if (empty($param['alias'])) {
                $this->error('参数错误');
            }
            if (empty($param['dept_id'])) {
                $this->error('数据不能为空');
            }
            $table = \app\spread\model\FreeTable::where('alias', $param['alias'])->find();
            $primary_key = $table['primary_key'];
            $table_name = $table['table_name'];

            $btn_config_id = $param['btn_config_id'];
            $dept_id = intval($param['dept_id']);
            $touid = intval($param['touid']);
            $ids = explode(',', $param['id']);

            // 固定表，读取url_value
            $url_data = array(
                "clue" => "crm/clue/index",
                "customer" => "crm/customer/index",
                "seas" => "crm/customer/seas",
                "contract" => "crm/contract/index",
                "receivable" => "crm/receivable/index",
            );
            if(in_array($param['alias'],array_keys($url_data))){
                $url_value = $url_data[$param['alias']];
            }else{
                $url_value = 'spread/free/index?alias=' . $param['alias'];
            }

            // 过滤没有权限的ID
            foreach ($ids as $key => $val) {
                if (!SpreadBtnConfig::checkSingleDataAuth($url_value, $param['alias'], $val)) {
                    unset($ids[$key]);
                }
            }
            if ($ids) {
                $ids = array_values($ids);
            } else {
                $this->error('没有符合条件的数据');
            }

            // 配置值
            $btn_config = SpreadBtnConfig::where('aid', $btn_config_id)->find();
            if (!$btn_config) {
                $this->error('配置不存在');
            }

            $spread_op_name = $btn_config['name'];
            $fieldvalue = json_decode($btn_config['system'], true);
            foreach ($fieldvalue as $key => $val) {
                if ($val['fieldType'] == 'dept') {
                    if ($dept_id) {
                        $data[$val['field_key']] = $dept_id;
                    }
                } else {
                    if ($touid) {
                        $data[$val['field_key']] = $touid;
                        $update_user_field = $val['field_key'];
                    }
                }
            }
            $data['update_time'] = time();
            $ids = is_array($ids) ? $ids : explode(',', $ids);

            if ($param['alias'] == 'freekehuguanli') {
                // 新增客户，验证最大客户数限制
                $is_enable_rule = MemberConfig::getSysConfigByName('is_enable_role');
                if ($is_enable_rule) {
                    $config_str = CrmRuleConfig::getConfigInfo(CrmRuleConfig::CUSTOMER_CONFIG);
                    $config_arr = json_decode($config_str['config'], true);
                    $flag_switch = isset($config_arr['is_limit_customer_num']) && $config_arr['is_limit_customer_num'];
                    // 验证修改的用户字段，是否和最大客户数判断的字段一致，不一致则不验证
                    $user_field_id = FreeField::where('field', $update_user_field)->where('table_name', 'lb_free_kehuguanli')->value('field_id');
                    $flag_res = CrmRuleCustomerNum::getInfo($user_field_id);
                    if ($config_arr && $flag_switch && $flag_res) {
                        $batch_num = count($ids);
                        $check_ret = Dispatch::checkCustomerMaxNum($touid, MemberID, $batch_num);
                        if ($check_ret['ret'] != 0) {
                            $msg = $check_ret['msg'];
                            $this->error($msg);
                        }
                    }
                }
                foreach ($ids as $id) {
                    // 记录转派日志
                    $before_uid = Db::table('lb_free_kehuguanli')->where('aid', $id)->value('xitongyuangong');
                    $before_user = User::where('aid', $before_uid)->value('nickname');
                    $after_user = User::where('aid', $touid)->value('nickname');
                    if ($spread_op_name == "转派") {
                        $repeat_log = "客户 由 {$before_user} 转派给 {$after_user}";
                    } else if ($spread_op_name=="分享"){
                        $repeat_log = "客户 已分享给 {$after_user}";
                    } else {
                        $repeat_log = "客户 {$spread_op_name} 给 {$after_user}";
                    }
                    CustomerLog::addLog($id, $repeat_log, 6);
                }
            }

            foreach ($ids as $key => $id) {
                config('free_table_name', $table_name);
                $Model = new \app\spread\model\Free();
                if ($primary_key == 'aid') {
                    $data['aid'] = $id;
                    $res = $Model::update($data);
                } else {
                    $data[$primary_key] = $id;
                    $res = $Model::update($data, [$primary_key => $id]);
                }

                // 改变后更新
                if (!SpreadBtnConfig::afterChange($param['alias'], $id, $btn_config_id)) {
                    $this->error('改变所属后更新失败');
                }
            }
            if ($res !== false) {
                // 更新单行数据
                $line_data = MapModel::leftJoinObj($this->module)->where($this->module . '.' . $primary_key, 'in', $ids)->find() ?: [];
                $raw_data = Db::table($table_name)->where($primary_key, '=', $ids[0])->where('is_del', '=', 0)->find() ?: [];
                $line_data = $line_data + $raw_data;
                $line_data = FreeProperty::handleDataToShow($this->module, $line_data);

                $this->success('操作成功', '', $line_data);
            } else {
                $this->error('操作失败');
            }
        } else {
            $param = $this->request->param();
            if (empty($param['id'])) {
                $this->error('缺少参数');
            }
            if (empty($param['alias'])) {
                $this->error('参数错误');
            }

            // 配置值
            $btn_config_id = $param['btn_config_id'];
            $btn_config = SpreadBtnConfig::where('aid', $btn_config_id)->find();
            if (!$btn_config) {
                $this->error('配置不存在');
            }
            $fieldvalue = json_decode($btn_config['system'], true);
            foreach ($fieldvalue as $key => $val) {
                if ($val['fieldType'] == 'dept') {
                    $field_type = 'dept';
                } else {
                    $field_type = 'user';
                }
            }
            $this->assign('field_type', $field_type);
            $this->assign('btn_config_id', $btn_config_id); // 按钮ID

            //部门
            $deptIds = [];
            $dept_ids = json_decode($btn_config['dept_ids'], true);
            foreach ($dept_ids as $key => $val) {
                $subDeptIds = \app\member\model\MemberDept::getSubDeptIds($val);
                $deptIds = array_merge($deptIds, $subDeptIds);
            }
            $deptIds = array_unique($deptIds);
            $deptIds = \app\member\model\MemberDept::where('aid', 'in', $deptIds)->column('name', 'aid');

            $authDept = \app\member\model\MemberDept::getAuthDept();
            if ($authDept["code"] == 0 && !empty($authDept["data"])) {
                foreach ($deptIds as $k => $v) {
                    if (!in_array($k, $authDept["data"])) {
                        unset($deptIds[$k]);
                    }
                }
            }
            $json_data = json_decode($btn_config['json_data'], true);
            // 如果没有这个参数，默认是可接单人员
            $is_crm = isset($json_data['showCanOrderUser']) ? $json_data['showCanOrderUser'] : 1;
            $this->assign('title', $btn_config['name']);
            $this->assign('is_crm', $is_crm);
            $this->assign('deptIds', $deptIds);

            return $this->fetch('spread@public/chose_user');
        }
    }

    /**
     * 打包下载附件
     * @date 2022-4-8 9:47
     */
    public function downloadFiles()
    {
        $param = $this->request->param();

        $alias = $param['alias'];
        $ids = $param['aid'];
        $ids = explode(',',$ids);
        $btn_config_id = $param['btn_config_id'];
        $table = \app\spread\model\FreeTable::where('alias', $alias)->find();
        $primary_key = $table['primary_key'];
        // 配置值
        $btn_config = SpreadBtnConfig::where('aid', $btn_config_id)->find();
        if (!$btn_config) {
            $this->error('配置不存在');
        }
        if ($alias == "seas") {
            $is_sea = 1;
            $alias = "customer";
        }else{
            $is_sea = 0;
        }

        $ids = is_array($ids) ? $ids : explode(',', $ids);
        $where[] = [$alias.'.'.$primary_key,'IN',$ids];
        $data = MapModel::leftJoinObj($alias, "", $is_sea, 1)->where($where)->select();
        $indexFields = FreeProperty::getIndexFields($alias, $is_sea, "all");

        foreach ($indexFields as $kk => $vv) {
            if($vv[7]['original_draw_type']){
                $type = $vv[7]['original_draw_type'];
            }else{
                $type = $vv[7]['type'];
            }
            if(in_array($type,['image', 'files', 'audio', 'video', 'images'])){
                $fields[] = $vv[0];
                $new_item[$vv[0]] = $type;
            }
        }

        foreach ($data as $key => $value){
            foreach ($value as $k => $v){
                if(!in_array($k,$fields)){
                    unset($data[$key][$k]);
                }
            }
        }
        $this->success('操作成功', '', $data);
    }


    //扫码枪页面
    public function scan_code()
    {
        $param = $this->request->param();
        $alias = $param['alias'];
        $ids = $param['r_id_val'];
        $btn_id = $param['btn_id'];
        $r_id_name = $param['r_id_name'];
        $table_info = FreeTable::where('alias',$alias)->field('aid,table_name')->find();
        $btnConfig = SpreadBtnConfig::where(['aid'=>$btn_id,'table_id'=>$table_info['aid']])->find();
        if(!$btnConfig){
            $this->error('扫码枪按钮配置有误');
        }
        $record = json_decode($btnConfig['record'],true);
        $scan_code = json_decode($btnConfig['scan_code'],true);
        $record_alias = FreeTable::where('aid',$record['table_id'])->value('alias');
        $scan_code_alias = FreeTable::where('aid',$scan_code['table_id'])->value('alias');
        //列表显示字段
        if($btnConfig['type'] == 5){
            $indexFields = FreeProperty::getIndexFields($record_alias);
        }
        if($btnConfig['type'] == 6){
            $indexFields = FreeProperty::getIndexFields($scan_code_alias);
        }
        $page_title = $btnConfig['name'];
        $this->assign('r_id_val',$ids);
        $this->assign('btn_config_aid',$btn_id);
        $this->assign('r_id_name',$r_id_name);
        $this->assign('btn_type',$btnConfig['type']);
        return Format::ins()
            ->setPrimaryKey('aid')
            ->setIsAdmin(false)
            ->addColumns($indexFields)
            ->setRightButtons($right_button)
            ->setPageTitle($page_title)
            ->fetch('spread@public/scan_code');
    }

    /**
     * 快速编辑
     * @param array $record
     */
    public function quickEdit($record = [])
    {
        halt($this->request->param());
        $field = input('post.name', '');
        $value = input('post.value', '');
        $type = input('post.type', '');
        $id = input('post.pk', '');
        $pk = input('post.primary_key', '');
        $table = input('post._t', '');
        if (empty($value) && $value != 0) {
            $this->error(lang('更改的内容不能为空'));
        }
        $field == '' && $this->error(lang('缺少字段名'));
        $id == '' && $this->error(lang('缺少主键值'));
        $table == '' && $this->error(lang('缺少主键值'));

        $result = Db::table($table)->where($pk, $id)->setField($field, $value);
        if (false !== $result) {
            $this->success(lang('操作成功'));
        } else {
            $this->error(lang('操作失败'));
        }
    }


    public static function checkAuthBtn($btn_data = [], $auth = [])
    {
        if (empty($btn_data) || empty($auth)) {
            return [];
        }

        foreach ($btn_data as $k => $v) {
            // 非超管/子管理员账号，过滤按钮展示
            if (!in_array(1, $auth['roles']) && !$auth['is_sub_admin'] && isset($v['user']) && !empty($v['user'])) {
                $btn_uids = array_column($v['user'], 'aid');
                if (!in_array($auth['uid'], $btn_uids)) {
                    unset($btn_data[$k]);
                }
            }

            if (!in_array(1, $auth['roles']) && !$auth['is_sub_admin'] && isset($v['role']) && !empty($v['role'])) {
                $btn_roles = array_column($v['role'], 'aid');
                if (empty(array_intersect($auth['roles'], $btn_roles))) {
                    unset($btn_data[$k]);
                }
            }

            if (in_array($v['ident'], ['edit','delete'])) {
                //非超级管理员，不能编辑他人数据 编辑按钮增加条件，排除条件增加派单确认，放入公海，OKR的KR
                if (!in_array(1, $auth['roles']) && !in_array(1, $auth['auth_edit_arr']) && !in_array($v['title'],['派单确认','放入公海']) && $auth['module'] != 'okrresults') {
                    $btn_data[$k]['extra'][] = [
                        'field' => 'create_id',
                        'compare' => '3',
                        'dataVal' => $auth['nickname'],
                        'logic' => '1',
                    ];
                }
            }
        }

        return array_values($btn_data);
    }
}